尽管有Javadoc,算法只能使用地址作为输入。这意味着即使新对象在伊甸园空间中使用相同的地址,它们也不会具有相同的哈希码。
它可能正在使用许多算法,但并非所有算法都使用该地址。
注意:hashCode() 是 31 位。
顺便说一句,您可以在热点上设置它。Unsafe.putInt(object, 1, value)
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