CodesJava

Easy learning with example program codes

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.codesjava;
 
public class Test {
	public static void main(String args[]){
		Site site1 = new Site("codesjava", 1);
		Site site2 = new Site("codesjava", 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.codesjava;
 
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("codesjava", 1);
		Site site2 = new Site("codesjava", 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-codesjava, 1-codesjava]
HashMap Elements: {1-codesjava=First site, 1-codesjava=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.codesjava;
 
public class Test {
	public static void main(String args[]){
		Site site1 = new Site("codesjava", 1);
		Site site2 = new Site("codesjava", 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.codesjava;
 
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("codesjava", 1);
		Site site2 = new Site("codesjava", 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-codesjava, 1-codesjava]
HashMap Elements: {1-codesjava=First site, 1-codesjava=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.codesjava;
 
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("codesjava", 1);
		Site site2 = new Site("codesjava", 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-codesjava]
HashMap Elements: {1-codesjava=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 follow and like us:
Posted in Java   


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki