What is the need to Override Hashcode() and equals() method

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with 46 Comments on What is the need to Override Hashcode() and equals() method

Although there are lots of material are available on internet and API document about the necessity of the overriding the hashcode() and equals() method in Java but lots of new developers still not able to understand the necessity of hashcode() method.
In this article, I will try to explain step by step the need of overriding hashcode() method in Java.

Although there are lots of materials are available on internet and API document about the necessity of the overriding the hashcode() and equals() method in Java but lots of new developers still not able to understand the necessity of hashcode() method.
In this article, I will try to explain step by step the need of overriding hashcode() method in Java.

Few Thump rules:

  • If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.
  • It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.

JVM assigns unique hashcode value to each object when they are created in memory and if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.

As the question comes in your mind that equals() method is used to compare objects that they are having same value or not but why should we override the hashcode method ?

The answer to the question is for the hash technique based data structures like HashMap and HashTable.

How Hashcode works in java
How Hashcode works in java

As you can see in above diagram that every object is placed in Hash bucket depending on the hashcode they have. It is not necessary that every different object must have different hashcode. hashcode is used to narrow the search result. When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and if yes then it checks for the equals() method. If two objects are same then HashMap will not add that key instead it will replace the old value by new one.

What will happen if I don’t override the hashcode method?
Ans : If the object does not implement hashcode() method and used as key then we will not get the object back as shown in below code.


Code without implementation of equals() and hashcode()

package com.G2.Collections;

import java.util.HashMap;

class Movie {
	private String name, actor;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getActor() {
		return actor;
	}

	public void setActor(String actor) {
		this.actor = actor;
	}

	public int getReleaseYr() {
		return releaseYr;
	}

	public void setReleaseYr(int releaseYr) {
		this.releaseYr = releaseYr;
	}

	private int releaseYr;
}

public class HashMapDemo {

	public static void main(String[] args) {

		Movie m = new Movie();
		m.setActor("Akshay");
		m.setName("Thank You");
		m.setReleaseYr(2011);

		Movie m1 = new Movie();
		m1.setActor("Akshay");
		m1.setName("Khiladi");
		m1.setReleaseYr(1993);

		Movie m2 = new Movie();
		m2.setActor("Akshay");
		m2.setName("Taskvir");
		m2.setReleaseYr(2010);

		Movie m3 = new Movie();
		m3.setActor("Akshay");
		m3.setName("Taskvir");
		m3.setReleaseYr(2010);

		HashMap<Movie, String> map = new HashMap<Movie, String>();
		map.put(m, "ThankYou");
		map.put(m1, "Khiladi");
		map.put(m2, "Tasvir");
		map.put(m3, "Duplicate Tasvir");

		//Iterate over HashMap
		for (Movie mm : map.keySet()) {
			System.out.println(map.get(mm).toString());
		}

		Movie m4 = new Movie();
		m4.setActor("Akshay");
		m4.setName("Taskvir");
		m4.setReleaseYr(2010);

/* We are trying to retrieve m2, by creating object m4 with exact values as of m2, However Hashcode method is not implemented and that why we are not able to get Object m2 */
		if(map.get(m4) == null ){
			System.out.println("----------------");
			System.out.println("Object not found");
			System.out.println("----------------");
		}else{
			System.out.println(map.get(m4).toString());
		}
	}
}

Output:
Khiladi
Tasvir
ThankYou
Duplicate Tasvir
—————-
Object not found
—————-

As you can see in above program :

  1. Duplicate objects are added in Hashmap as a key (Because we have not overided the hashcode and equals method)
  2. We are not able to get back object from map (Because hashcode is not implemented)

Same program with equals and hashcode implementation:

package com.G2.Collections;

import java.util.HashMap;

class Movie {
	private String name, actor;

	@Override
	public boolean equals(Object o) {
		Movie m = (Movie) o;
		return m.actor.equals(this.actor) && m.name.equals(this.name) && m.releaseYr == this.releaseYr;
	}

	@Override
	public int hashCode() {
		return actor.hashCode() + name.hashCode() + releaseYr;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getActor() {
		return actor;
	}

	public void setActor(String actor) {
		this.actor = actor;
	}

	public int getReleaseYr() {
		return releaseYr;
	}

	public void setReleaseYr(int releaseYr) {
		this.releaseYr = releaseYr;
	}

	private int releaseYr;
}

public class HashMapDemo {

	public static void main(String[] args) {

		Movie m = new Movie();
		m.setActor("Akshay");
		m.setName("Thank You");
		m.setReleaseYr(2011);

		Movie m1 = new Movie();
		m1.setActor("Akshay");
		m1.setName("Khiladi");
		m1.setReleaseYr(1993);

		Movie m2 = new Movie();
		m2.setActor("Akshay");
		m2.setName("Taskvir");
		m2.setReleaseYr(2010);

		Movie m3 = new Movie();
		m3.setActor("Akshay");
		m3.setName("Taskvir");
		m3.setReleaseYr(2010);

		HashMap<Movie, String> map = new HashMap<Movie, String>();
		map.put(m, "ThankYou");
		map.put(m1, "Khiladi");
		map.put(m2, "Tasvir");
		map.put(m3, "Duplicate Tasvir");

		// Iterate over HashMap
		for (Movie mm : map.keySet()) {
			System.out.println(map.get(mm).toString());
		}

		Movie m4 = new Movie();
		m4.setActor("Akshay");
		m4.setName("Taskvir");
		m4.setReleaseYr(2010);

		if (map.get(m4) == null) {
			System.out.println("----------------");
			System.out.println("Object not found");
			System.out.println("----------------");
		} else {
			System.out.println("----------------");
			System.out.println(map.get(m4).toString());
			System.out.println("----------------");
		}
	}
}

Output:
Khiladi
Duplicate Tasvir
ThankYou
—————-
Duplicate Tasvir
—————-
As you can see :

  • Duplicate Keys are not added instead there values are replaced.
  • Now the object is retrieved from the Map.

Ques : How to iterate over keyset of HashMap in JDK 4 and 5?
Ans : This is the common question asked in interview.

In JAVA 5 : we can use advance for loop as shown in above code, use map.keySet(). This will return the Set (As Keys must be unique)

In JAVA 4 : use map.keySet() and get the Iterator object using map.iterate() . then using while loop , get the value for each key.

Related posts

46 thoughts on “What is the need to Override Hashcode() and equals() method”

  1. This statement is absolutely wrong “What will happen if I don’t override the hashcode method?
    Ans : If the object does not implement hashcode() method and used as key then we will not get the object back as shown in below code.”
    This should be “What will happen if I don’t override equals ” and when you do override equals methods you must override hashcode to fulfill the general contract that “all equal objects according to .equals method must have same hashcode”

    1. hey shailendra, you are right that to be objects equal, both method must be overrided. But my emphasys is on need of hashcode() method and that is correct. You can refer java api and try to run program also.

    2. Sorry but Can i know if you are not putting m4 object in map, How you are able to retrieve it.

      for (Movie mm : map.keySet()) {

      System.out.println(map.get(mm).toString());

      }

      Movie m4 = new Movie();

      m4.setActor(“Akshay”);

      m4.setName(“Taskvir”);

      m4.setReleaseYr(2010);

      if (map.get(m4) == null) {

      System.out.println(“—————-“);

      System.out.println(“Object not found”);

      System.out.println(“—————-“);
      } else {

      System.out.println(“—————-“);

      System.out.println(map.get(m4).toString());

      System.out.println(“—————-“);

      }

      }

      Output:

      Khiladi

      Duplicate Tasvir

      ThankYou

      —————-

      Duplicate Tasvir // M4 object

      —————-

      1. You must note that object m2,m3 and m4 will have same hashcode (as implemented in example).
        so when you are doing map.get(m4) internally it gets hashcode and based on hashcode it will get index of bucket .
        and once he will have bucket based on .equals method it will fetch the value “Duplicate Tasvir” .

        Hope you will get it.

  2. Hi shailendra,
    statement is perfect. He already specified that to be object same equal method is required. But what if somebody does not override hashcode ? Comparing two object will return true if they are same and hashcode is not implemented. But when object is used as a key in hashmap’ object cannot be retrieved. Try to run the program, you will get.
    Rahul

  3. Hi,

    I did not understand ur code, as u have not added m4 object in map (like map.put(m4, “Tasvir”);), then why are u trying to retrieve from hashmap like map.get(m4). If it is not added u r not able to retrieve and getting output as object not found.

      1. line 70 in first prg and 81 in second prg does not add m4 to map, then acessing m4 will always give you  null. Can you please correct it.

        1. Hi Amit,
          I have not added the object in a map because i am trying to use the object as a “Key” and it will not work if i will not override “Hashcode” and “equal” methods.
          That is the reason i have used code like this.

          1. Yes got your explanation now.. hashcode of m2, m3 and m4 will be same after overriding equals and hashcode method , so it is retrieving the value.

  4. Perfect demonstration of hashcode and equals and it cleared most of my doubts.Thanx u v.much.Well i think u r akshay kumar’s fan.

  5. Hi

    I have one doubt in the above code.

    JVM assigns unique hashcode value to each object when they are created in memory .How it’s possible to assign same hashcode to objects

    Can anybody explain?

  6. It is just a perfect explanation with perfect example.. It cleared all my doubts.. Thanks for the explanation..

  7. though object m2 and m4 has got same value(logically equals ) but they are actually not same object

    m2==m4 wont return TRUE.

    now if I do m4=m2 , which means m2==m4 -> TRUE.

    So is this explanation meaning , logically equals objects should be treated as same key in hash map and they should be stored in the same bucket in hashtable.

    Is my understanding correct.

  8. Hi Jitendra,
    just one question .. it is silly but i was having doubt that when this equal() method gets called in your program. I debugged the program and saw after putting values in map it goes there, but why?
    Thanks in advance.

  9. The article is very helpful.Though the flow of call between equal(),hash code() and the main() is not clear. It will be very helpful ,If anyone explain the flow .

  10. Hi,

    Here we are not adding the m4 as key to Hashmap,But still we can able to get that from Hashmap.Can pls explain it clearly.

  11. i cant understand what u r saying because i read ur concept…but now i understood ur explanation because i practiced ur example step by step…..
    m4 object is checking purpose he used…that object is in map or not….

  12. Hi Jitendra,
    Thanks,My questions is that Object class provides default implemtation then why we should override these methods what is the actual difference between Objects equal method and override custom class equal method?

    1. In Object class .equals() method is used for reference comparison. In String class and all Wrapper classes, .equals() method is overridden for content comparison. in this example program m1 and m2 are two movie objects with different references though we are setting same values. if we don’t override .equals() method, then HashMap is comparing their references and treating them as unique keys.

  13. Hi Jitendra,

    After overriding equals and hashcode methods, when you try to retrieve using m4 object, you are able to retrieve object with value ‘Duplicate Tasvir’. Why not object with value ‘Tasvir’ retrieved? if I want to retrieve object with value ‘Tasvir’ how?

  14. This is the first reason should be explained everywhere for the question “why hascode() is needed?”. But everybody starts explaining how its being used in hashtables and hashmaps. Thanks Jitendra for this blog.

Leave a Reply

Your email address will not be published. Required fields are marked *