如果我使用Set类似于此:
Set<node> s=new TreeSet<node>();
class node {
private int x;
private int y;
}
Run Code Online (Sandbox Code Playgroud)
这是否可以接受,因为它是一个TreeSet,它还会对它进行排序吗?
Jon*_*eet 20
如果没有你的实现Comparable<Node>,它将无法对它进行排序,并且在你覆盖equals()和之前它不适合于设置操作hashCode().(你不具备覆盖equals并hashCode进行TreeSet工作,但它会是有意义的这样做.)
像这样的东西:
final class Node implements Comparable<Node> {
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;
}
}
Run Code Online (Sandbox Code Playgroud)
(请注意,按照惯例,类名称Node不是node.)
Node需要实现Comparable,或者您需要传递一个可以比较两个Node对象的自定义Comparator.此外,任何基于散列的集合都依赖于适当地覆盖equals()和hashcode()方法的对象.