私は、同等(おそらく関連性がない)を実装する独自のクラスを構築しました。また、HashSetを使用してアイテムを格納しようとすると、HashSetは時にはアイテムがHashSetにない。私はそれが基準チェックと関係があると思ったが、そうではないことを確認した。なにが問題ですか?Java TreeSetが期待どおりに動作しない
頂点クラスequals
とgetHashcode
:
public class Vertex implements Comparable<Vertex>{
// some code ...
@Override
public boolean equals(Object obj) {
Vertex other = (Vertex) obj;
return this.getPosition().equals(other.getPosition());
}
@Override
public int hashCode() {
int hashCode1 = Integer.parseInt(this.getPosition().getX() + "" + this.getPosition().getY());
return hashCode1;
}
}
位置クラス:
public class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public boolean equals(Object obj) {
Position other = (Position) obj;
return this.x == other.x && this.y == other.y;
}
@Override
public String toString() {
//return String.format("x = %d, y = %d", x, y);
return String.format("(%d, %d)", x, y);
}
}
EDIT:ここ実装
public static void test(Vertex[][] grid) {
TreeSet<Vertex> someSet = new TreeSet<Vertex>(){{
add(new Vertex(new Position(3, 4), false));
add(new Vertex(new Position(0, 5), false));
}};
Vertex v = new Vertex(new Position(2, 5), false);
if (someSet.contains(v)) {
System.out.println("error");
} else {
System.out.println("ok");
}
}
上記プリントerror
あります。
ハッシュコードは一意ではありません。たとえば、(2,31)&(21,3) – Sanjeev
あなたのキーは何ですか?あなたのキーは等しく、ハッシュコードは完全に実装されていますか? I –
投稿したクラス(つまり、HashSetを作成するコード)を使用するコードを含める必要があります。 – Eran