Equals and Hashcode method are available through java.lang.Object class. The object class is default inherited to each and every class and java.lang.* the package is also the default import package in java. So, all the methods of Object class are default inherited to every class in java.
Object class provides the default implementation of equals and hashcode method. The default functionality of equals is to compare two object equality by using the “==” operator. Check below code of equals method taken from Object class:
public boolean equals(Object obj) {
return (this == obj);
}
Note: Binary operator i.e.: “==” and equals method are different that we discuss them in another post.
As per the above java code, the equals method performs reference equality between two objects. We don’t have any access to the memory address in java, so we can’t say that reference equality check is memory address equality check in java.
Every object in Java has a unique Integer value which is hashcode. Hashcode method is a native method in the object class.
public native int hashCode();
The hashcode value is used in HashMap to find bucket location. Not just hashMap, almost every hash-based data structure.
Contract between Equals and hashCode method:
Equals and hashCode method helps in comparing two objects that are equal or not. Two different objects can possibly have the same hashcode but it doesn’t mean they are equal because hashcode is just for finding the bucket location whether it’s fetching the object or storing the object in any hash-based data structure.
Single bucket location can able to store more than one object. HashMap is work on basis of hashing principle and backed by an array (table). Every index of the array is called bucket location and every index of array internally stores data/object in the node form which is nothing but LinkedList based data structure. Suppose two object are not equal but their hashCode is same means two object of HashMap is stored in the same bucket location due to the same hashcode then we use the equals method to find the correct object.
Note: As per the above criteria, if hashCode is changed which is never happen but we never ever able to fetch back the object from any hash-based data structure. So, hashCode never changed from birth to destruction of an object.
As we find, how in hashmap hashcode and equals method play their role in the equality of objects by maintaining the contract with each other. In the same way, we have to override the equals and hashcode method for equality of objects.
How to override equals and hashcode method in Part-2.