A Deep Dive into Java 8 equals() and hashcode()

DN Tech
Geek Culture
Published in
5 min readJun 4, 2022

--

What is equals()?

In the default code in Object.java, equals() is defined as follows:

public boolean equals(Object obj) {
return (this == obj);
}

The method uses “==” to compare the two objects. “==” compares the reference addresses in Java. If both objects refer to the same address, they are equal by default.

What is hashcode()?

In the same Object.java class, hashcode() is defined as a native function.

public native int hashCode();

According to the official documented comments, hashcode():

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.

As we can see, the purpose of hashcode() is to be used in the hash-related classes including HashMap, HashSet, HashTable, and ConcurrentHashmap.

Some questions to consider…

If two objects have the same hashcode, do they equal each other?

Not necessarily. As hashcode() returns a 32-bit integer, it is unavoidable that different objects could have the same hashcode value. A similar analogy could be that if two people…

--

--

DN Tech
Geek Culture

Backend Software Engineer who shares about my daily work bits