为什么 HashSet.contains() returns 结果错误?

Why HashSet.contains() returns wrong result?

我有以下 classes 和方法:

public class Node<T> {
    private T val ;
    private Node parent;

    public Node(T s, Node p)
    {
        val=s;
        parent=p;
    }

    public Node(T s)
    {
        val=s;
    }

    public boolean equals(Node s)
    {
        return this.val.equals(s.val);
    }

    public int hashCode()
    {
        return val.hashCode();
    }

T 的实现:

public class Point{
    private int x;
    private int y;

    public Point(int x,int y)
    {
        this.x=x;
        this.y=y;
    }

    public String toString()
    {
        return "("+x+","+y+")";
    }
    public boolean equals(Object obj)
    {
        if(obj instanceof Point) {
            Point a=(Point)obj;
            return a.x==this.x && a.y==this.y;
        }
        return false;

    }
   public int hashCode()
    {
    return toString().hashCode();

    }

主要方法:

public static void main(String[] args) {
    HashSet<Node> set= new HashSet<>();
    Node<Point> a = new Node(new Point(0,0));
    Node<Point> b = new Node(new Point(0,0));
    set.add(a);
    System.out.println("checking if a equals to b : " + (a.equals(b) && a.hashCode() == b.hashCode())); // returns true
    System.out.println("Checking if set contains b : "+ set.contains(b)); // returns false
}

知道为什么我在 set.contains 中出错了吗?根据我的阅读,第一个检查基本上是 set.contains 所做的。我在 Point class 和 Node class.

中实现了 hashCode 和 equals

您的 Node class 的 equals 方法不会覆盖 superclass,因为它具有不同的签名,它采用 Node 对象参数而不是 Object 的任何实例。 更改为

public boolean equals(Object s) {
    if (!(s instanceof Node))
        return false;
    return this.val.equals(((Node) s).val);
}