This is a most common and very basic concept which get ask in interviews. equals() and hashCode() contract methods provided by java.lang.Object class.
Let’s discuss equals() and hashcode() one by one.
This method check for content equality. The two objects are equal if they stores at the same memory location.
Syntax:
public boolean equals(Object obj)
There are some rules defined by JAVA SE that mush be follow by equals () method as shown below:
This method returns an integer value. This method used to compare objects and need to be overridden in every class which overrides equals() method.
Syntax
public int hashCode()
hashCode() method internally calculate the hashCode of current Object and return int value.
NOTE: Objects that are equal will always be having same hash code. Vice versa not correct, two unequal Objects can have same or different hashcode.
In below example two different variables a and b are having same String value as Apple. Checking equality on line number 5 “a.equals(b)” returns true as both the String got matched.
OUTPUT:
a.equals(b) = true
Now, in below example we created two different objects with same values at line number 14 and 15. While checking equality at line number 16 it returned false.
OUTPUT:
st1.equals(st2) = false
In below example, we have proved st1.equals(st2) as true after overriding equals() and hashCode() methods.
st1.equals(st2) = true
In below example we have overridden the equals method to check object equality.
equals() method override:
On line number 13, it checks if two objects have the same reference. If yes, they are referring to the same object and this means, they are equal by default.
On line number 17, it checks if an object belongs to the same class or not. There is no need to compare if the object is not an instance of the required class. In this case comparison object is incorrect and will always be unequal.
Finally, on line number 22, current object compare field value with object passed in a parameter. Objects will be unequal by default if any of the field value didn’t get match..
According to Java SE, two objects are equal if and only if their hash codes are also equal. To demonstrate this condition, the hashCode () method must be overridden. On line number 25, after overriding the hashCode() method, it is returning id as a hashcode as this will satisfy the condition.
OUTPUT:
Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.
📝 Blogs
javadoubts.com © All rights reserved