hashCode () has little to do with memory locations. Although this may look like an address, it is just a randomly generated number.
I did not expect it to always stand out from the same segment, but I needed to know if the objects were selected one at a time, since my result showed a bit of such a pattern
It can be expected that this is a random number.
If you run this in OpenJDK or Oracle access point, you will get.
import sun.misc.Unsafe; import java.lang.reflect.Field; public class ObjectAddress { public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object(); Object o3 = new Object(); Object[] os = {o1, o2, o3}; System.out.println("Before using hashCode"); for (int i = 0; i < os.length; i++) { int address = UNSAFE.getInt(os, UNSAFE.arrayBaseOffset(Object[].class) + i * 4); int hashCode = UNSAFE.getInt(os[i], 1L); System.out.println(i + ": " + Integer.toHexString(address) + " hashCode " + Integer.toHexString(hashCode)); os[i].hashCode(); } System.out.println("After using hashCode"); for (int i = 0; i < os.length; i++) { int address = UNSAFE.getInt(os, UNSAFE.arrayBaseOffset(Object[].class) + i * 4); int hashCode = UNSAFE.getInt(os[i], 1L); System.out.println(i + ": " + Integer.toHexString(address) + " hashCode " + Integer.toHexString(hashCode) + " for " + os[i]); UNSAFE.putInt(os[i], 1L, 0x12345678); } System.out.println("After setting the hashCode"); for (int i = 0; i < os.length; i++) { int address = UNSAFE.getInt(os, UNSAFE.arrayBaseOffset(Object[].class) + i * 4); int hashCode = UNSAFE.getInt(os[i], 1L); System.out.println(i + ": " + Integer.toHexString(address) + " hashCode " + Integer.toHexString(hashCode) + " for " + os[i]); os[i].hashCode(); } } static final Unsafe UNSAFE; static { try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); UNSAFE = (Unsafe) theUnsafe.get(null); } catch (Exception e) { throw new AssertionError(e); } } }
you will get something like
Before using hashCode 0: d8e78160 hashCode 0 1: d8e78170 hashCode 0 2: d8e78180 hashCode 0 After using hashCode 0: d8e78160 hashCode 68111f9b for java.lang.Object@68111f9b 1: d8e78170 hashCode 3c322e7d for java.lang.Object@3c322e7d 2: d8e78180 hashCode 3e2f1b1a for java.lang.Object@3e2f1b1a After setting the hashCode 0: d8e78160 hashCode 12345678 for java.lang.Object@12345678 1: d8e78170 hashCode 12345678 for java.lang.Object@12345678 2: d8e78180 hashCode 12345678 for java.lang.Object@12345678
You can see that each object has 16 bytes.
source share