hashCode and equals method in java

The hashCode() method in java is an Object class method. It returns a hash code value (an integer number) for the object which represents the memory address of the object. It is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

Conceptually:

The hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set or map. This bucket number is the address of the element inside the set or map.

When we call contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

Java hashCode method example

package com.w3spoint;
 
public class Test {
	public static void main(String args[]){
		String str1 = "w3spoint";
		String str2 = "w3spoint";
		//Will generate same hash code
		System.out.println(str1.hashCode());
		System.out.println(str2.hashCode());
 
		String str3 = new String("w3spoint");
		String str4 = new String("w3spoint");
		//Will generate same hash code
		System.out.println(str3.hashCode());
		System.out.println(str4.hashCode());
 
		Site site1 = new Site("w3spoint", 1);
		Site site2 = new Site("w3spoint", 1);
		//Will generate different hash code
		System.out.println(site1.hashCode());
		System.out.println(site2.hashCode());		
	}
}
 
class Site{
	private String name;
	private int id;
 
	public Site(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}	
}

Output

-1108854968
-1108854968
-1108854968
-1108854968
366712642
1829164700

equals()

The equals() method in java is an Object class method. It return true for two non-null reference values x and y if and only if x and y refer to the same object. That means, basic implementation of equals method compares the memory location and not compare the object values.

Syntax:

public boolean equals(Object obj)

Java equals method example

package com.w3spoint;
 
public class Test {
	public static void main(String args[]){
		String str1 = "w3spoint";
		String str2 = "w3spoint";
		//Return true, compare reference
		System.out.println(str1.equals(str2));
 
		String str3 = new String("w3spoint");
		String str4 = new String("w3spoint");
		//Return true, compare reference
		System.out.println(str3.equals(str4));
 
		Site site1 = new Site("w3spoint", 1);
		Site site2 = new Site("w3spoint", 1);
		//Return false, compare reference
		System.out.println(site1.equals(site2));		
	}
}
 
class Site{
	private String name;
	private int id;
 
	public Site(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
}

Output

true
true
false

Why to override hashCode() and equals() method in java

We need to override hashCode() method in every class that overrides equals() method because if we do not do this it may result in a violation of the above mention general contract between hashCode and equals

The general contract of hashCode and equals is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • 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 hashtables.

Let’s start with the first case: override equals method.

package com.w3spoint;
 
public class Test {
	public static void main(String args[]){
		Site site1 = new Site("w3spoint", 1);
		Site site2 = new Site("w3spoint", 1);
		//It will return true because we override the equals method
		System.out.println(site1.equals(site2));		
	}
}
 
class Site{
	private String name;
	private int id;
 
	public Site(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	@Override
	public boolean equals(final Object obj) {
		if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final Site siteObject = (Site) obj;
        if(this.getName() == siteObject.getName() && 
        		this.getId() == siteObject.getId())
        	return true; 
        else
        	return false;
	}	
 
}

Output

true

The above program return true because we override the equals method based on name and id i.e. two site objects which have same name and id are considered to be equal. Now let us think about set and map. Set does not contains a duplicate element and map does not contains duplicate key. Let us try to implement the set and map with above example. We override the toString method to clearly understand the implementation.

package com.w3spoint;
 
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
public class Test {
	public static void main(String args[]){
		Site site1 = new Site("w3spoint", 1);
		Site site2 = new Site("w3spoint", 1);
		//It will return true because we override the equals method
		System.out.println(site1.equals(site2));
 
		Set<Site> hashSet = new HashSet<>();
		hashSet.add(site1);
		hashSet.add(site2);		
		System.out.println("HashSet Elements: " + hashSet);
 
		Map<Site, String> hashMap = new HashMap<>();
		hashMap.put(site1, "First site");
		hashMap.put(site2, "Second site");
		System.out.println("HashMap Elements: " + hashMap);
	}
}
 
class Site{
	private String name;
	private int id;
 
	public Site(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}	
 
	@Override
	public String toString() {
		return this.getId() + "-" + this.getName();
	}
 
	@Override
	public boolean equals(final Object obj) {
		if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final Site siteObject = (Site) obj;
        if(this.getName() == siteObject.getName() && 
        		this.getId() == siteObject.getId())
        	return true; 
        else
        	return false;
	}	
 
}

Output

true
HashSet Elements: [1-w3spoint, 1-w3spoint]
HashMap Elements: {1-w3spoint=First site, 1-w3spoint=Second site}

In the result, we can clearly see that in both set and map there are duplicate elements and duplicate keys respectively. It violets the set and map implementations.

Let’s consider the second case: override hashCode method.

package com.w3spoint;
 
public class Test {
	public static void main(String args[]){
		Site site1 = new Site("w3spoint", 1);
		Site site2 = new Site("w3spoint", 1);
		//It will return false
		System.out.println(site1.equals(site2));		
	}
}
 
class Site{
	private String name;
	private int id;
 
	public Site(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	@Override
	public int hashCode() {
		//For simplicity we are returning id as hashCode value 
		return this.id;
	}
 
}

Output

false

The above program return false because we override the hashCode method only. For comparing two objects, equals method only compares the references. Now let us think about set and map. Set does not contains a duplicate element and map does not contains duplicate key. Let us try to implement the set and map with above example. We override the toString method to clearly understand the implementation.

Note: Set is also using map as an implementation internally.

package com.w3spoint;
 
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
public class Test {
	public static void main(String args[]){
		Site site1 = new Site("w3spoint", 1);
		Site site2 = new Site("w3spoint", 1);
		//It will return true because we override the equals method
		System.out.println(site1.equals(site2));
 
		Set<Site> hashSet = new HashSet<>();
		hashSet.add(site1);
		hashSet.add(site2);		
		System.out.println("HashSet Elements: " + hashSet);
 
		Map<Site, String> hashMap = new HashMap<>();
		hashMap.put(site1, "First site");
		hashMap.put(site2, "Second site");
		System.out.println("HashMap Elements: " + hashMap);
	}
}
 
class Site{
	private String name;
	private int id;
 
	public Site(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}	
 
	@Override
	public String toString() {
		return this.getId() + "-" + this.getName();
	}
 
	@Override
	public int hashCode() {
		//For simplicity we are returning id as hashCode value 
		return this.id;
	}
 
}

Output

false
HashSet Elements: [1-w3spoint, 1-w3spoint]
HashMap Elements: {1-w3spoint=First site, 1-w3spoint=Second site}

Let us understand the put method of map with hashCode. For first object hashCode returns 1 based on which index value is calculated. It returns 1 in our case so at index 1, first object will be inserted which contains four elements hash, key, value and next. When second object is inserted into map, hashCode again returns 1 and equals method comes into existence to compare key value. Ideally as two objects looks identical so first object should be replaced by second but as equals method is not implemented and by default it only compare references, hence two objects are treated as different that’s why second object will be inserted into linked list. As location for both objects are at index 1 so next of first object will contains the address of second object.

In the result, we can clearly see that in both set and map there are duplicate elements and duplicate keys respectively. It violets the set and map implementations.

Above problems can be resolved by overriding both hashCode and equals method.

package com.w3spoint;
 
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
public class Test {
	public static void main(String args[]){
		Site site1 = new Site("w3spoint", 1);
		Site site2 = new Site("w3spoint", 1);
		//It will return true because we override the equals method
		System.out.println(site1.equals(site2));
 
		Set<Site> hashSet = new HashSet<>();
		hashSet.add(site1);
		hashSet.add(site2);		
		System.out.println("HashSet Elements: " + hashSet);
 
		Map<Site, String> hashMap = new HashMap<>();
		hashMap.put(site1, "First site");
		hashMap.put(site2, "Second site");
		System.out.println("HashMap Elements: " + hashMap);
	}
}
 
class Site{
	private String name;
	private int id;
 
	public Site(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}	
 
	@Override
	public String toString() {
		return this.getId() + "-" + this.getName();
	}
 
	@Override
	public int hashCode() {
		//For simplicity we are returning id as hashCode value 
		return this.id;
	}
 
	@Override
	public boolean equals(final Object obj) {
		if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final Site siteObject = (Site) obj;
        if(this.getName() == siteObject.getName() && 
        		this.getId() == siteObject.getId())
        	return true; 
        else
        	return false;
	}	
 
}

Output

true
HashSet Elements: [1-w3spoint]
HashMap Elements: {1-w3spoint=Second site}

In the result, we can clearly see that in both set and map there is no duplicate elements and duplicate keys respectively which follows the set and map implementations.

Please Share