FIFO tie breaker in Comparator?
For a homework, I need to compare Nodes based on a heuristic so that I can put them in a TreeSet. However, when 开发者_开发知识库the heuristic values for two Nodes are equal I need some way to break the tie.
I'm not allowed to modify the Node class provided and as far as I can tell there aren't any other values / properties of Node that would help me break the tie that I'm not already using. (We're dealing with puzzles, not that it really matters.) Is there some way I could break ties based on when I added them to my TreeSet? I just don't know how to go about it....
I saw an example in the documentation for a Priority Blocking Queue but I want to use the Comparator interface, and I can't get it to work.
Thanks in advance; any tips / hints are very much appreciated.
Are you allowed to create a wrapper for Nodes?
public class NodeWrapper implements Comparable<NodeWrapper> {
private static AtomicLong serialNumGenerator = new AtomicLong(0L);
private final Node node;
private final long serialNum;
public NodeWrapper(Node node) {
this.node = node;
this.serialNum = serialNumGenerator.getAndIncrement();
}
@Override
public int compareTo(NodeWrapper other) {
int compare = this.node.compareTo(other.node);
if (compare == 0) {
compare = (this.serialNum < other.serialNum)
? -1
: ((this.serialNum > other.serialNum) ? 1 : 0);
}
return compare;
}
// implement other methods including equals() and hashCode()
}
You can try System.identityHashCode(Object) to get an int that you can use to sort the objects.
精彩评论