如果我使用的是与此类似的 Set
:
Set<node> s=new TreeSet<node>();
class node {
private int x;
private int y;
}
这是可以接受的吗,既然它是一个 TreeSet,它也会对它进行排序吗?
最佳答案
如果不实现 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;
}
}
(请注意,按照惯例,类名是 Node
,而不是 node
。)
关于java - 如何在 TreeSet 中使用自定义类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416176/