Set is not working with overridden equals

纵饮孤独 提交于 2019-12-11 02:09:54

问题


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:


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.



来源:https://stackoverflow.com/questions/9134254/set-is-not-working-with-overridden-equals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!