尽管有 Javadoc,算法只能使用地址作为输入。这意味着即使新对象在伊甸园空间中使用相同的地址,它们也不会具有相同的 hashCode。
它可能正在使用许多算法,但并非所有算法都使用该地址。
注意:hashCode() 是 31 位的。
顺便说一句,您可以Unsafe.putInt(object, 1, value)
在 Hotspot 上进行设置。
Set<Integer> ints = new LinkedHashSet<>();
int negative = 0, nonneg = 0;
for (int i = 0; i < 100; i++) {
System.gc();
for (int j = 0; j < 100; j++) {
int h = new Object().hashCode();
ints.add(h);
if (h < 0) negative++;
else nonneg++;
}
}
System.out.println("unique: " + ints.size() + " negative: " + negative + " non-neg: " + nonneg);
印刷
unique: 10000 negative: 0 non-neg: 10000
使用不安全
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
Object o = new Object();
System.out.println("From header " + Integer.toHexString(unsafe.getInt(o, 1L)));
// sets the hashCode lazily
System.out.println("o.hashCode() " + Integer.toHexString(o.hashCode()));
// it's here now.
System.out.println("after hashCode() From header " + Integer.toHexString(unsafe.getInt(o, 1L)));
unsafe.putInt(o, 1L, 0x12345678);
System.out.println("after change o.hashCode() " + Integer.toHexString(o.hashCode()));
印刷
From header 0
o.hashCode() 2260e277
after hashCode() From header 2260e277
after change o.hashCode() 12345678