我希望我的Set中只有2个元素,但是在打印时我会收到3个元素!我怎样才能定义唯一性?
public class test {
public static void main(String[] args) {
class bin {
int a;
int b;
bin (int a, int b){
this.a=a;
this.b=b;
}
public boolean Equals(bin me) {
if(this.a==me.a && this.b==me.b)
return true;
else
return false;
}
@Override
public String toString() {
return a+" "+b;
}
}
Set q= new HashSet();
q.add(new bin(11,23));
q.add(new bin(11,23));
q.add(new bin(44,25));
System.out.println(q);
}
}
解决方法:
这里有两个问题
> equals应为小写并接受Object
>您还必须覆盖hashCode
修改后的代码如下所示.请注意,实现远非完美,因为在equals中你应该检查null以及是否可以进行类型转换等.另外hashCode只是一个例子,但是如何实现这样的东西是另一个主题.
import java.util.Set;
import java.util.HashSet;
public class test {
public static void main(String[] args) {
class bin{
int a;
int b;
bin (int a, int b){
this.a=a;
this.b=b;
}
@Override
public boolean equals(Object me) {
bin binMe = (bin)me;
if(this.a==binMe.a && this.b==binMe.b)
return true;
else
return false;
}
@Override
public int hashCode() {
return this.a + this.b;
}
@Override
public String toString() {
return a+" "+b;
}
}
Set q= new HashSet();
q.add(new bin(11,24));
q.add(new bin(11,24));
q.add(new bin(10,25));
q.add(new bin(44,25));
System.out.println(q);
}
}
结果:
[11 24, 10 25, 44 25]
标签:java,set,hashset
来源: https://codeday.me/bug/20190519/1134877.html