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.