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

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.

Posted

in

by

Tags:


Related Posts

Comments

49 responses to “What is the need to Override Hashcode() and equals() method”

  1. Shailendra kumar Avatar
    Shailendra kumar

    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. Jitendra Zaa Avatar

      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. bheemrav mahoviya Avatar
      bheemrav mahoviya

      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. Jitendra Zaa Avatar

        line 50-68, all objects are inserted in map. Now to get value, we just need to create an object and that will act as key, so need to insert in map again.

      2. Arun G Avatar
        Arun G

        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.

      3. Jenny Avatar
        Jenny

        So true. m4 is not added to map

  2. rahul sahoo Avatar
    rahul sahoo

    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. Ramya Avatar
    Ramya

    It is said above that when v try ti insert key into hashmap…what is key…please may i know this…

    1. Jitendra Zaa Avatar

      Here, i mean any object like String, Integer or Custom Object inserted with its value .

      Thanks,
      Jitendra Zaa

  4. DHARA Avatar
    DHARA

    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. Jitendra Zaa Avatar

      Hi Dhara,
      Please check line 70 in first code and line 81 in second code snippet, i have added object m4.
      Thanks,
      Jitendra Zaa

      1. Amitparashar Avatar
        Amitparashar

        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.  Avatar
          Anonymous

          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. pjoshi Avatar
            pjoshi

            Your explanation is not correct, if you dont add object into map then it will return null only,

          2. Jitendra Zaa Avatar

            Try to run above code, you will get it.

          3. Palak Joshi Raval Avatar
            Palak Joshi Raval

            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. Dheeresh Singh Avatar
            Dheeresh Singh

            Pjoshi : Jitendra Zaa is absolutly correct, although the m4 object not been added in the map, but m4 is the exact copy of m2 and m2 is getting used here as a KEY, so it will return m2 object value.
            Please correct me if i am wrong.

  5. sanjay Avatar
    sanjay

    hey,
    that was excellent representation, now i know why sholud we ovverride equls() and hashcode.
    Thanks
    K.K

  6. Sanket Avatar
    Sanket

    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.

  7. venkat Avatar
    venkat

    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?

    1. Shashi Neggi Avatar
      Shashi Neggi

       hi u can override any objects hashcode method and give it any number.

  8. Guest Avatar
    Guest

    Confusion about M4 object, you have not insert the m4 into the map…

    1. JitendraZaa Avatar
      JitendraZaa

      Because… i am using that object as a Key to retrieve value.

  9. Jaweriya Nazneen Ali Avatar
    Jaweriya Nazneen Ali

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

  10. sasi Avatar
    sasi

    It was good Explanation, Thanks for your post.

  11. Arvind Avatar
    Arvind

    I got the cocept.
    Good explanation…thanks

  12. gauri Avatar
    gauri

    this was really of very good help.. thanks you so very much

  13. khushbu Avatar
    khushbu

    very well explained ..Thanks

  14. crystal Avatar
    crystal

    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.

  15. Dheeraj Barve Avatar
    Dheeraj Barve

    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.

    1. Jitendra Zaa Avatar

      On line number – 86, when u call get method, it is internally called.

  16. kashim Avatar
    kashim

    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 .

  17. prasant Avatar
    prasant

    nice topic
    Thanks

  18. Anu Avatar
    Anu

    Very well explained! It makes the whole concept crystal clear!

  19. Sourabh Avatar
    Sourabh

    Very nice self explanatory example

    1. JitendraZaa Avatar
      JitendraZaa

      Thanks Saurabh

  20. Ganesh Annamaina Avatar
    Ganesh Annamaina

    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.

  21. Ashish Avatar
    Ashish

    very good explanation . Thanks Jitendra

  22. naveen Avatar
    naveen

    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….

  23. Sandip Mangale Avatar
    Sandip Mangale

    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. Manoj Chiruvolu Avatar
      Manoj Chiruvolu

      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.

  24. satyanarayna Avatar
    satyanarayna

    Good explanation

  25. Edgar Avatar
    Edgar

    Yes! Finally got it! Thank you!

  26. Venu Gopal Avatar
    Venu Gopal

    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?

  27. Tejashree Parab Avatar
    Tejashree Parab

    Explanation was really good. Got the concept very well.
    Thanks..!

  28. Harish Kumara Avatar
    Harish Kumara

    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.

  29. Dheeresh Singh Avatar
    Dheeresh Singh

    Jitendra Zaa is absolutly correct, although the m4 object not been added in the map, but m4 is the exact copy of m2 and m2 is getting used here as a KEY, so it will return m2 object value.
    Please correct me if i am wrong.

  30. Priya Avatar
    Priya

    Can anyone please explain how the search operation becomes easier because of this hash code in java?
    Thanks in advance.

Leave a Reply to venkatCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading