如果没有实现Comparable< Node>,它将无法对其进行排序,并且在重写equals()和hashCode()之前它不适合于设置操作. (您不必为TreeSet重写equals和hashCode,但这样做是有意义的.)
像这样的东西:
final class Node implements Comparable {
private final int x;
private final int y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
@Override public boolean equals(Object other) {
if (!(other instanceof Node)) {
return false;
}
Node otherNode = (Node) other;
return x == otherNode.x && y == otherNode.y;
}
@Override public int hashCode() {
return x * 31 + y * 17; // For example...
}
@Override public int compareTo(Node other) {
// As of Java 7, this can be replaced with
// return x != other.x ? Integer.compare(x, other.x)
// : Integer.compare(y, other.y);
if (x < other.x || (x == other.x && y < other.y)) {
return -1;
}
return x == other.x && y == other.y ? 0 : 1;
}
}
(请注意,按照惯例,类名称将是Node,而不是节点.)