Sau*_*akh 7 java string caching immutability
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
Run Code Online (Sandbox Code Playgroud)
即使我在反射的帮助下更改了字符,也会保留相同的哈希码值.
这里有什么我需要知道的吗?
Sot*_*lis 14
A String
意味着不可改变.因此,没有必要重新计算哈希码.它在内部缓存在一个名为hash
type 的字段中int
.
String#hashCode()
实现为(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;
}
Run Code Online (Sandbox Code Playgroud)
其中hash
最初具有的值0
.它只会在第一次调用方法时计算出来.
正如评论中所述,使用反射会破坏对象的不变性.
归档时间: |
|
查看次数: |
510 次 |
最近记录: |