结论
a.equals(b) 为真,但是两者的hashcode如果不相同的话,在集合中的判断就会出现问题。将a、b同时加入散列存储结构map、set时,就可能出现数据结构中存在两个值相等的对象的情况,从而导致混淆。
例子
String a=new String("123");
String b=new String("123");
System.out.println(a==b); //false
System.out.println(a.equals(b)); //true
System.out.println(a.hashCode()==b.hashCode()); //true ,如果不重写hashcode()这里会变成false
Set<String> set=new HashSet<>();
set.add(a);
System.out.println(set.contains(b)); //true ,如果不重写hashcode()这里会变成false
字符串中重写的equals()方法
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
// instanceof: 判断前面的对象是否属于后面的类,或者属于其子类
// 如果值是字符串,则执行下面部分
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
// 如果两个字符串长度相同,则放入数组中进行一一比较
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
hashCode()的重写
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
// 把每个值遍历
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
参考:
https://blog.csdn.net/CY2333333/article/details/119010159