Skip to content

equal hashCode

serhij.zolotukhin edited this page Jun 29, 2026 · 1 revision

The equals() Method

Reflexive: x.equals(x) must return true for any non-null x. Symmetric: x.equals(y) should return the same as y.equals(x). Transitive: if x.equals(y) and y.equals(z) then x.equals(z) must hold. Consistent: repeated calls return the same result if objects don’t change. Non-null: x.equals(null) must always return false.

The hashCode() Method

Consistency: The hash code of an object must remain the same across multiple calls within the same execution if the object’s state (fields used in equals()) doesn’t change. Equals-consistency: If x.equals(y) is true, then x.hashCode() == y.hashCode() must hold. Collision allowed: It’s allowed (though not ideal) for unequal objects to have the same hash code (a collision).

https://medium.com/the-java-interview-playbook/equals-hashcode-methods-in-java-e99bc1066851

The compareTo

-Ensure Symmetry: If a.compareTo(b) returns a negative value, then b.compareTo(a) should return a positive value. -Consistent with equals(): If compareTo() returns zero, then equals() should ideally return true. Though not required by the language, it helps avoid confusing behaviors.

https://dev.to/tpointtechadu/mastering-compareto-in-java-a-complete-guide-with-examples-c83 https://medium.com/@sp00m/java-object-identity-or-how-to-override-equals-hashcode-and-compareto-400fd4547fe0

What's the default hash value of an object on 64 bit JVM

How to calculate identity hashCode is JVM specific.

As to HotSpot JVM, it uses random number generator for initial calculation of identity hashCode. After the hashCode is calculated for the first time, it is saved in the object header so that subsequent calls to identityHashCode will return the same value.

Actually the algorithm of generating identity hashCode can be altered by -XX:hashCode JVM option. Look at the sources. There are the following options:

-XX:hashCode=0 - global Park-Miller RNG (default until Java 7) -XX:hashCode=1 - function(obj_address, global_state) -XX:hashCode=2 - constant 1. All objects will have the same hashCode. Just for testing. -XX:hashCode=3 - incremental counter. -XX:hashCode=4 - lower 32 bits of the object address in the Heap -XX:hashCode=5 - thread-local Marsaglia's Xor-shift RNG (default since Java 8)

https://github.com/openjdk/jdk/blob/master/src/java.base/share/native/libjava/System.c https://github.com/openjdk/jdk/blob/37ae15a4896c700e0a47a43de3330e8879d147c2/src/hotspot/share/prims/jvm.cpp#L631 https://github.com/openjdk/jdk/blob/37ae15a4896c700e0a47a43de3330e8879d147c2/src/hotspot/share/runtime/synchronizer.cpp#L642

My side bar

Clone this wiki locally