I was trying to use set. so i tried this way
HashSet set=new HashSet();
Points p1 = new Points(10, 20);
Points p2 = new Points(10, 20);
System.out.println(set.add(p1)); // output true
System.out.println(set.add(p2)); // output false
I know my first output will be true and second will be false as Set will not allow duplicate elements. And, i also know Set achieve this by using equals(Object o) method. Which comes from java Object class with following signature.
public boolean equals(Object o) {}
For testing this little bit deeper i wrote my own class
class testSet{
private int x;
private int y;
public testSet(int xa, int ya){
this.x=xa;
this.y=ya;
}
@Override
public boolean equals(Object o){
if (o instanceof testSet){
testSet ts=(testSet)o;
return ts.x==this.x && ts.y==this.y;
}
return false;
}
}
Now i am expecting following code will behave same as Point class
HashSet set=new HashSet();
testSet set_a=new testSet(3,4);
testSet set_b=new testSet(3,4);
System.out.println(set.add(set_a)); //output expected true
System.out.println(set.add(set_b)); //output expected false
So i am expecting first output will be true and second one false . But it is always returning true for both case. But did working for Point class. And i tried with following two Point implementations
android.graphics.Point
java.awt.point
So what i did wrong? Thanks for helping guys.
You need to override
hashCode
as well asequals
. The general contract ofhashCode
is that if two objects are equal (in the sense ofequals
), then they have the same hash code.