HashCode and Equals methods in java

We will see hashcode() and equals() methods in java.

These methods can be found in the Object class and hence available to all java classes.Using these two methods, an object can be stored or retrieved from a Hashtable, HashMap or HashSet.

hashcode() and equals() method

hashcode():You might know if you put entry in Map, first hashcode is calculated and this hashcode is used to find index of bucket where this entry will get stored in Map. If you don’t override hashcode method, it will  return integer representation of memory address.

equals():You have to override equals method, when you want to define equality between two object. If you don’t override this method, it will check for reference equality(==) i.e. if tow reference refers to same object or not.

Lets see below example for more details  – 
package com.myjavablog.javainterview.hashcodeandequals;
public class Person {
private String name;
private int age;public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Person class has two attributes name and age.
How can you compare two Person objects? So here you have equals() method from Object class which you can implement in Person class. You can compare two Person objects using particular attribute either name or age from Person class .
Below program will check equality for Person objects –
package com.myjavablog.javainterview.hashcodeandequals;
/**
* @author anupb
*
*/
public class EqualityCheck {/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stubPerson p1 = new Person();
p1.setName("Anup");
Person p2 = new Person();
p2.setName("Anup");System.out.println("Are these two persons same: " + p1.equals(p2));
}}
Output:
Are these two persons same: false
Here you have not implemented equals method in Person class. So above equality check happens on memory address and not on the attributes of the object. Above two objects p1 and p2 points to different memory addresses. Ideally these two Persons are same but above equality check fails.
So now we will add equals() method to Person class which actually compares the objects –

@Override

public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

Now lets see the output of EqualityCheck –
Are these two persons same: true
This is because you have overridden equals method .
Now lets put these person objects into HashMap – 
Key is Person object
Value – City name to which he belongs (String type)
package com.myjavablog.javainterview.hashcodeandequals;import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;/**
* @author anupb
*
*/
public class HashMapEqualityCheck {/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stubPerson p1 = new Person();
p1.setName("Anup");
Person p2 = new Person();
p2.setName("Anup");

Map<Person, String> personMap = new HashMap<>();
personMap.put(p1, "Pune");
personMap.put(p2, "Pune");

Iterator<Person> itr = personMap.keySet().iterator();

while (itr.hasNext()) {

Person p = itr.next();
String city = personMap.get(p);
System.out.println("Person: " + p.getName() + " City: " + city);
}
}

}

Output:
Person: Anup City: Pune
Person: Anup City: Pune
Now you must be wondering , how HashMap contains two keys with are equal. This is because HashMap first calculates hashcode of the key. It will then calculate the bucket index in the HashMap. If two hashcodes are equal then it will use equals method to compare these two objects and because hashcode for above two person objects uses default hashcode method,Both will have different memory address hence different hashcode.
Now override below hashcode method –
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
Now if you run HashMapEqualityCheck , you can see only one key will be inserted as below –
Person: Anup City: Pune
So now hashcode for above two objects p1 and p2 are same, so Both will be point to same bucket,now equals method will be used to compare them which  will return true.
So the contract says “if you override equals() method then you must override hashCode() method”
hashcode()
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

Key points to remember:

  1. If you are overriding equals method then you should override hashcode() also.
  2. If two objects are equal then they must have same hashcode.
  3. If two objects have same hashcode then they may or may not be equal
  4. Always use same attributes to generate equals and hashcode as in our case we have used name.

Leave a Comment

Bitnami