Sobes.tech
Senior

What is the difference between hashCode() and System.identityHashCode()?

sobes.tech AI

Answer from AI

The hashCode() method in Java is an object method that is usually overridden to ensure proper functioning in collections such as HashMap or HashSet. It returns a hash code based on the object's logic, for example, on the values of its fields.

System.identityHashCode(Object obj) returns a hash code based on the internal address of the object in memory, ignoring the overridden hashCode() method. That is, even if a class overrides hashCode(), calling System.identityHashCode() will give a unique identifier related to its actual location.

Example:

String a = new String("test");
String b = new String("test");

System.out.println(a.hashCode() == b.hashCode()); // true, because the contents are the same
System.out.println(System.identityHashCode(a) == System.identityHashCode(b)); // false, different objects

Thus, hashCode() is used for logical comparison, while System.identityHashCode() is used for identifying a specific object in memory.

What is the difference between hashCode() and… - sobes.tech