我一直在尝试实现equals和hashCode方法,所以我可以使用arrayList的remove方法.
当我执行以下
Node a = new Node(new Coord(0,0));
System.out.println(a.equals(nodes.get(0)));
System.out.println(nodes.get(0).equals(a));
System.out.println(a.hashCode() == nodes.get(0).hashCode());
System.out.println(nodes.remove(a));
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
true
true
true
false
Run Code Online (Sandbox Code Playgroud)
问题是,当第4个返回false时,输出的前3个如何返回true.remove方法应该遇到nodes.get(0)并将它与a进行比较.
这些是我的equals和hashCode方法:
public int hashCode() {
return coord.hashCode();
}
public boolean equals(Node node) {
return (node != null) && (this.hashCode() == node.hashCode());
}
Run Code Online (Sandbox Code Playgroud)
它调用方法coord.hashCode(),定义为:
public int hashCode() {
int hash = 23;
hash = 31 * hash + this.x;
hash = 31 * hash + this.y;
return hash;
}
Run Code Online (Sandbox Code Playgroud)