小编hal*_*bæk的帖子

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

我一直在尝试实现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)

java equals arraylist hashcode

2
推荐指数
1
解决办法
2951
查看次数

标签 统计

arraylist ×1

equals ×1

hashcode ×1

java ×1