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

时间:2013-06-23 21:40:09

标签: 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).hashCode());
    System.out.println(nodes.remove(a));

我得到以下输出:

true
true
true
false

问题是,当第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());
}

调用方法coord.hashCode(),定义为:

public int hashCode() {
    int hash = 23;
    hash = 31 * hash + this.x;
    hash = 31 * hash + this.y;
    return hash;
}

2 个答案:

答案 0 :(得分:11)

您当前的equals()方法无法覆盖Object.equals()重载

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

public boolean equals(Object o) {
    return (o instanceof Node) && (this.hashCode() == o.hashCode());
}

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


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

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

答案 1 :(得分:1)

您无法使用hashCode方法比较equals:

a.equals(b)== true,a.hashCode()是强制性的== b.hashCode()

a.hashCode()== b.hashCode(),a.equals(b)NOT是强制性的,更多可以是== 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;
}   
相关问题