equals和hashCode定义,arrayList方法仍然无法正常工作

hal*_*bæk 2 java equals arraylist 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).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)

Boh*_*ian 11

您当前的equals()方法不会覆盖Object.equals(),它会重载它.

更改equals()为接受Object参数:

public boolean equals(Object o) {
    return (o instanceof Node) && (this.hashCode() == o.hashCode());
}
Run Code Online (Sandbox Code Playgroud)

Java具有@Override可以放在方法上的注释,因此编译器会告诉您方法实际上是否覆盖.使用它是一种很好的做法,因此您可以在编译时避免这样的问题.


请注意,您的equals实现有一个错误:您不应该比较哈希代码 - 两个"不相等"的对象可能(不幸地)共享相同的哈希代码.

比较字段,而不是哈希码.