Set is not working with overridden equals

2019-07-19 05:48发布

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.

1条回答
在下西门庆
2楼-- · 2019-07-19 05:54

You need to override hashCode as well as equals. The general contract of hashCode is that if two objects are equal (in the sense of equals), then they have the same hash code.

查看更多
登录 后发表回答