I investigated the implementation of equals () and hashCode () in java.lang.Object.
Object.equals() The implementation in JDK 8 just compares the reference values as shown below.
src/share/classes/java/lang/Object.java
public boolean equals(Object obj) {
return (this == obj);
}
src/share/classes/java/lang/Object.java#l149
Since the reference value is a pointer to an object, Object.equals () returns true only if it is the same instance.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
The reference value (also just a reference) is a pointer to an object or null. null is a special reference value that does not refer to an object.
Object.hashCode() hashCode () depends on the JVM implementation.
share/classes/java/lang/Object.java#l100
public native int hashCode();
share/classes/java/lang/Object.java#l100
It is explained in great detail in the article below. How does the default hashCode() work?
After all, the implementation of OpenJDK in the JVM is
is what they said. XorShift is an algorithm that can generate (fast) pseudo-random numbers with only exclusive OR and bit shift. Once generated, the hash code is recorded in an area called Object Header, which is owned by each instance. The second and subsequent calls to hashCode () will return the hash code recorded in the Object Header.
The code to generate the hash code in OpenJDK8 is as follows.
src/share/vm/runtime/synchronizer.cpp
// Marsaglia's xor-shift scheme with thread-specific state
// This is probably the best overall implementation -- we'll
// likely make this the default in future releases.
unsigned t = Self->_hashStateX ;
t ^= (t << 11) ;
Self->_hashStateX = Self->_hashStateY ;
Self->_hashStateY = Self->_hashStateZ ;
Self->_hashStateZ = Self->_hashStateW ;
unsigned v = Self->_hashStateW ;
v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;
Self->_hashStateW = v ;
value = v ;
src/share/vm/runtime/synchronizer.cpp
Generate a hash code using the thread member variables _hashStateX
and _hashStateW
.
I don't understand the xor-shift algorithm, but by moving the values of _hashStateX, _hashStateY, and _hashStateW to the variable with the previous name in alphabetical order and making _hashStateW the generated hash code, the next call We make it possible to generate unique values at times.
_hashState is initialized as follows when a thread is created.
src/share/vm/runtime/thread.cpp
_hashStateX = os::random() ;
_hashStateY = 842502087 ;
_hashStateZ = 0x8767 ; // (int)(3579807591LL & 0xffff) ;
_hashStateW = 273326509 ;
src/share/vm/runtime/thread.cpp
Object.equals () is a comparison of reference values. The value of Object.hashCode () is a random number generated at the first call in each instance, and the second and subsequent calls return the generated random number.
Recommended Posts