0
//1
int\[\]\[\] arr = new int\[2\]\[2\];
System.out.println(arr\[0\]); // \[I@7d6f77cc
System.out.println(arr\[1\]); // \[I@5aaa6d82
System.out.println(System.identityHashCode(arr\[0\])); // 2104457164
System.out.println(System.identityHashCode(arr\[1\])); // 1521118594

//2
int\[\]\[\] arr = new int\[2\]\[2\];
System.out.println(arr\[1\]); // \[I@7d6f77cc
System.out.println(arr\[0\]); // \[I@5aaa6d82
System.out.println(System.identityHashCode(arr\[1\])); // 2104457164
System.out.println(System.identityHashCode(arr\[0\])); // 1521118594

//3
int\[\] arr2 = new int\[2\];
System.out.println(System.identityHashCode(arr2\[0\])); // 2104457164
System.out.println(System.identityHashCode(arr2)); // 1521118594
System.out.println(System.identityHashCode(arr2\[1\])); // 2104457164

//4
int\[\] arr2 = new int\[2\];
System.out.println(System.identityHashCode(arr2)); // 2104457164
System.out.println(System.identityHashCode(arr2\[0\])); // 1521118594
System.out.println(System.identityHashCode(arr2\[1\])); // 2104457164

AFAIK, the hashcode is determined when an object is created. However, it seems to be determined when accessed, and I'm not sure about the mechanism behind it.

(It's like in the Copenhagen interpretation of quantum mechanics, the act of observing a particle leads to the collapse of its wavefunction and the determination of its state.)

An uninitialized int array element will be set to 0.

However, what about the hashcode of an uninitialized array element? It seems like it determined when the element is accessed for the first time, not when the array is created.

I have tested it multiple times and found that the hashcode is always determined in the order of access. However, due to my poor Googling skills, I couldn't find any relevant information about this, and I'm not sure where to look for it. I'm wondering when the hashcode is determined.

ChoCoc
  • 1

1 Answers1

0

The hashcode of any element (int, string, object...) is determined by it's value, (of for your own class you can override this and make your own hash function). So there is no determining the hashcode, it's calculated using a function and thus determined whenever you call the hash function. You can read more about java's hash function here.

Note that 2 different element's can have the same hash value. It could be interesting to look into HashMaps and HashSet to see how hash values are utilized.

Hope this helps, if you want a more detailed explanation feel free to hit me up.

aronb
  • 41
  • 5