Java 已定义equals和hashCode,arrayList方法仍不起作用
我一直在尝试实现equals和hashCode方法,因此我可以使用arrayList的remove方法 当我执行以下命令时Java 已定义equals和hashCode,arrayList方法仍不起作用,java,arraylist,equals,hashcode,Java,Arraylist,Equals,Hashcode,我一直在尝试实现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).h
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));
我得到以下输出:
true
true
true
false
问题是,当第四个返回false时,输出的前3个如何返回true。remove方法应遇到节点。获取(0)并将其与a进行比较
以下是我的equals和hashCode方法:
public int hashCode() {
return coord.hashCode();
}
public boolean equals(Node node) {
return (node != null) && (this.hashCode() == node.hashCode());
}
调用方法coord.hashCode(),该方法定义为:
public int hashCode() {
int hash = 23;
hash = 31 * hash + this.x;
hash = 31 * hash + this.y;
return hash;
}
您当前的equals()
方法没有覆盖对象。equals()
,它会重载它
更改equals()
以接受对象
参数:
public boolean equals(Object o) {
return (o instanceof Node) && (this.hashCode() == o.hashCode());
}
Java有一个注释,您可以在方法上添加注释,因此编译器将告诉您方法是否实际上没有重写。使用它是一种很好的做法,因此可以避免在编译时出现类似的问题
请注意,equals实现有一个bug:您不应该比较哈希代码-两个“不等”对象可能(不幸地)共享相同的哈希代码
比较字段,而不是哈希代码。无法使用哈希代码方法比较相等项。原因: a、 等于(b)==true,强制要求a.hashCode()等于b.hashCode() a、 hashCode()==b.hashCode(),a.equals(b)不是必需的,更多可以==false 使用一个属性(x)实现的示例。通过eclipse生成:
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (x != other.x)
return false;
return true;
}
毫无疑问,这是一个故事。包括您的“节点”声明。您可以使用@Override(>=JDK5),以确保您定义的方法不会简单地重载父方法,而是真正地重写它。或者将(推荐的)@Override注释添加到您的实际方法实现中-这会立即揭示问题的原因。。。