今天比较空闲.无聊初次写点东西,有误地方欢迎大家提出,关于HashSet种重复值的判断问题,这种问题常常出现在java笔试当中,我们需要注意。我自己写了个demo测试,请大家看代码.
实体测试类
package com.lyy.interview;
public class Student {
private String uphone;
private String uname;
public String getUphone() {
return uphone;
}
public void setUphone(String uphone) {
this.uphone = uphone;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
@Override
public boolean equals(Object student) {
Student s = (Student) student;
if(this.uphone.equals(s.uphone)){
return true;
}
return false;
}
}
测试输出类
package com.lyy.interview;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
public class TestSet extends TestCase {
public void testSetRepeat(){
Student s1 = new Student();
s1.setUname("lyy");
s1.setUphone("123456");
Student s2 = new Student();
s2.setUname("lyy");
s2.setUphone("1234567");
Student s3 = new Student();
s3.setUname("lyyaa");
s3.setUphone("123456");
Student s4 = s3;
Set<Student> set = new HashSet<Student>();
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
System.out.println(s1.hashCode()== s3.hashCode());
System.out.println(s1.equals(s3));
System.out.println(set.size());
}
}
输出结果为
false
true
3
由此可见HashSet中只有当 obj1==obj2 时才判断为重复值 equals 不能判断