问题描述
String s1 = "String1";
System.out.println(s1.hashCode()); // return an integer i1
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] value = (char[])field.get(s1);
value[0] = 'J';
value[1] = 'a';
value[2] = 'v';
value[3] = 'a';
value[4] = '1';
System.out.println(s1.hashCode()); // return same value of integer i1
这里甚至在我用反射的帮助改变了字符后,相同的哈希码值是主要的。
Here even after I changed the characters with the help of reflection, same hash code value is mainatained.
这里有什么我需要知道的吗?
Is there anything I need to know here?
推荐答案
字符串
是不可变的。因此,没有必要重新计算哈希码。它在内部缓存在名为 hash
的字段中,类型为 int
。
A String
is meant to be immutable. As such, there is no point having to recalculate the hashcode. It is cached internally in a field called hash
of type int
.
String#hashCode()
实现为(Oracle JDK7)
String#hashCode()
is implemented as (Oracle JDK7)
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;
}
其中哈希
最初的值为 0
。它只会在第一次调用方法时计算。
where hash
initially has a value of 0
. It will only be calculated the first time the method is called.
如评论中所述,使用反射会破坏对象的不变性。
As stated in the comments, using reflection breaks the immutability of the object.
这篇关于是否真的缓存了java.lang.String的哈希码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!