java String hashcode到底是什么?
Object hashcode是什么?
直接看源码
effect java
String hashcode是什么?
字符串重写了equal方法,就必须要同时重写hashcode()——目的就是要确保上面规范里说的,equal相等,hashcode也必须要相等。
字符串的equal和hashcode都是基于字符串内容去计算的,由于字符串内容相同,所以equal就相同,hashcode也相同。
源码
equal方法,直接看代码注释
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
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]; //最核心的代码就是这里,其实就是基于字符串内容和公式,然后计算得到一个int类型的值——这个值就是所谓的hashcode
}
hash = h;
}
return h;
}
demo
//import lombok.extern.slf4j.Slf4j;
/**
* @author gzh
* @createTime 2022/1/16 6:44 AM
*/
//@Slf4j
public class Test2 {
public static void main(String[] args) {
String a = "gzh";
String b = "gzh";
if (a == b){
System.out.println(true);
//hashcode相同:因为equal相同,hashcode就必须相同——这个是因为都是基于字符串内容去计算的。
System.out.println(a.hashCode()); //变量计算的时候,也是基于变量的字符串内容计算的
System.out.println(b.hashCode());
System.out.println("gzh".hashCode()); //字符串内容计算的时候,仍然是基于字符串内容计算的
}else {
System.out.println(false);
}
// //
// String a2 = "123";
// String b2 = "123";
// if (a2 == b2){
// System.out.println(true);
// }else {
// System.out.println(false);
// }
}
}
总结,
- equal
字符串内容相同,所以比较的时候就是相同的,因为重写的equal就是基于字符串内容比较是否相等。
- hashcode
字符串内容相同,所以hashcode也相同——因为重写的hashcode也是基于字符串内容和公式计算得到的。
重写非String的hashcode
一般也是基于对象的内容,比如实体类,也是基于实体类的内容(各个字段的值)和某个公式,然后计算得到一个唯一的int类型的值。
转载自:https://juejin.cn/post/7053670026364059656