Set
これに似たものを使用していた場合:
Set<node> s=new TreeSet<node>();
class node {
private int x;
private int y;
}
これは受け入れられるでしょうか? TreeSet であるため、並べ替えも行われますか?
を実装せずにソートすることはできません。また、 andComparable<Node>
をオーバーライドするまでは、セット操作には適切ではありません。( and forを機能させるためにオーバーライドする必要はありませんが、そうすることは理にかなっています。)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
。)
Node は Comparable を実装するか、2 つの Node オブジェクトを比較できるカスタム Comparator を渡す必要があります。また、ハッシュベースのコレクションは、 equals() および hashcode() メソッドを適切にオーバーライドするオブジェクトに依存しています。
equals、hashCode を指定し、Comparable インターフェイスを実装する必要があります。
受け入れに関する限り、コードに問題はありません。ただし、Node
クラスを並べ替えるには、同等のインターフェイスを実装する必要があります。