-1

I have the following classes and methods :

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();
    }

Implementation of 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();

    }

Main Method:

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
}

Any idea why I'm getting false in set.contains ? From what I read the first check is basically what set.contains does. I implemented hashCode and equals in Point class and in Node class.

Naman
  • 23,555
  • 22
  • 173
  • 290
JeyJ
  • 1,970
  • 2
  • 17
  • 40
  • 2
    Your method signature for equals in Node is wrong. The argument should be of type Object, not type Node. Your current way, you're not overriding the equals method from the Object class – Erwin Bolwidt Jun 09 '19 at 10:28
  • 2
    Lesson learned here: use @ Override when overriding methods! – GhostCat Jun 09 '19 at 10:29
  • 1
    This question is example of why we should *always* add `@Override` annotation when we intend to override some method. More info [When do you use Java's @Override annotation and why?](https://stackoverflow.com/q/94361) – Pshemo Jun 09 '19 at 10:30
  • Understood, I will use @Override from now on. Thank u everyone ! – JeyJ Jun 09 '19 at 10:40

1 Answers1

2

Your Node class's equals method does not override the superclass since it has a different signature, it takes a Node object argument instead of any instance of Object. Change to

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