一、新建一个类Userfromboss ,其中有id和name属性,都是String类型的
二、写一个函数:
@Test
public void test(){
String a ="123";
String b ="123";
Set<String> set = new HashSet<String>();
set.add(a);
set.add(b);
System.out.println(set.size());
Set<Userfromboss> set1 = new HashSet<Userfromboss>();
Userfromboss u1 = new Userfromboss();
Userfromboss u2 = new Userfromboss();
u1.setId("1");
u1.setName("zhangsan");
u2.setId("1");
u2.setName("zhangsan");
set1.add(u1);
set1.add(u2);
System.out.println(set1.size());
}
打印结果为1,2。结果并不相同
三、修改Userfromboss ,重写这个类的equals和hashcode两个函数
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return this.getId().equals(((Userfromboss)obj).getId())&&this.getName().equals(((Userfromboss)obj).getName());
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return 1;
}
四。再回去打印一下,发现已经是1,1了
五。任意删掉一个重写的函数,打印结果是1,2
六。结论:hashset是同时比较equals和hashcode两个函数的。。同时打开String的源码。可以看到equals和hashcode两个函数如下:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
下次重新这两个函数的时候,不要自己重写了,要仿照string类的两个方法来重写哦。O(∩_∩)O~