是否真的缓存了java.lang.String的哈希码?

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 

即使我在reflection的帮助下更改了字符,也会保留相同的哈希码值。

这里有什么我需要知道的吗?

String意味着不可变。 因此,没有必要重新计算哈希码。 它在内部缓存在名为hash的类型为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; } 

hash最初的值为0 。 它仅在第一次调用方法时计算。

正如评论中所述,使用reflection会破坏对象的不变性。