集不适用于覆盖的等于 [英] Set is not working with overridden equals
问题描述
我正在尝试使用set.所以我尝试了这种方式
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
我知道我的第一个输出将是true,第二个输出将是false,因为Set不允许重复的元素.而且,我也知道Set通过使用equals(Object o)方法来实现这一点.它来自具有以下签名的java Object类.
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;
}
}
现在我希望以下代码的行为与Point类相同
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
因此,我希望第一个输出为true,第二个输出为false.但这两种情况总是返回true.但是确实为Point类工作.我尝试了以下两个Point实现
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.
推荐答案
您需要覆盖hashCode
和equals
. hashCode
的一般约定是,如果两个对象相等(在equals
的意义上),则它们具有相同的哈希码.
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.
这篇关于集不适用于覆盖的等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!