hashCode And equals Methods Override

In this Java tutorial, we will discuss about hashCode, equals methods and what role they play in an object. Through this article we will find answer for the following questions,

  • What is the purpose of hashCode and equals methods?
  • How hashCode and equals are implemented?
  • Why hashCode should also be overridden when equals is overridden?

equal

equals Method

equals() method is used to determine the equality of two objects. To bring in little bit of Mathematics flavor lets see the properties of equality. When we say equality, it should adhere by the following properties,

  • Reflexive: Always, a = a. In Java, a.equals(a) should always be true.
  • Symmetric: If a = b, then b = a. In Java, if a.equals(b) is true, then b.equals(a) should be true.
  • Transitive: If a = b and b = c, then a = c. In Java, if a.equals(b) and b.equals(c) is true, then a.equals(c) should be true.

Above three points are some theory and do not worry about it much.

For a primitive type, determining the equality is simple. We all know an int value of 10 is always equal to 10. But this equals() method is about equality of two objects. When we say object, it will have properties. To decide about equality those properties are considered. It is not necessary that all properties must be taken into account to determine the equality and with respect to the class definition and context it can be decided. Then the equals() method can be overridden.

Override equals Method

Let us take an example scenario to understand equals() method and study how to override it in our custom implementation. We have a Tiger class and two instances of Tiger are equal if they have the same color and stripePattern is our definition of equality. In our example, though there is an additional property ‘height’, it is excluded from the equals definition to denote that it is entirely our choice.

package com.javapapers.java;

public class Tiger {
	private String color;
	private String stripePattern;
	private int height;

	@Override
	public boolean equals(Object object) {
		boolean result = false;
		if (object == null || object.getClass() != getClass()) {
			result = false;
		} else {
			Tiger tiger = (Tiger) object;
			if (this.color == tiger.getColor()
					&& this.stripePattern == tiger.getStripePattern()) {
				result = true;
			}
		}
		return result;
	}

	// just omitted null checks
	@Override
	public int hashCode() {
		int hash = 3;
		hash = 7 * hash + this.color.hashCode();
		hash = 7 * hash + this.stripePattern.hashCode();
		return hash;
	}

	public static void main(String args[]) {
		Tiger bengalTiger1 = new Tiger("Yellow", "Dense", 3);
		Tiger bengalTiger2 = new Tiger("Yellow", "Dense", 2);
		Tiger siberianTiger = new Tiger("White", "Sparse", 4);
		System.out.println("bengalTiger1 and bengalTiger2: "
				+ bengalTiger1.equals(bengalTiger2));
		System.out.println("bengalTiger1 and siberianTiger: "
				+ bengalTiger1.equals(siberianTiger));

		System.out.println("bengalTiger1 hashCode: " + bengalTiger1.hashCode());
		System.out.println("bengalTiger2 hashCode: " + bengalTiger2.hashCode());
		System.out.println("siberianTiger hashCode: "
				+ siberianTiger.hashCode());
	}

	public String getColor() {
		return color;
	}

	public String getStripePattern() {
		return stripePattern;
	}

	public Tiger(String color, String stripePattern, int height) {
		this.color = color;
		this.stripePattern = stripePattern;
		this.height = height;

	}
}

BengalTiger

Example Code Output:

bengalTiger1 and bengalTiger2: true
bengalTiger1 and siberianTiger: false
bengalTiger1 hashCode: 1398212510
bengalTiger2 hashCode: 1398212510
siberianTiger hashCode: –1227465966

SiberianTiger

hashCode Method

In the above example did you notice we have overridden another method hashCode() along with equals()? There is an importance to it. We must override hashCode() when we override equals(). Why hashCode should also be overridden when equals is overridden? Because, they both serve the same purpose but in different contexts.

hashCode() method is used in hashtables to determine the equality of  keys. If you want more details about hashCode, their default implementation, buckets, different hashing techniques you should go through my earliest tutorial on Java Hashtable. I guarantee you will enjoy, just read it :-).

When an application is executed, the hashcode (an integer) returned for an object should be same till another execution of that application. Now coming to the important point which is the contract between hashCode and equals method,

  • if two objects are equal, that is obj1.equals(obj2) is true then, obj1.hashCode() and obj2.hashCode() must return same integer.

Override hashCode Method

To honor the above contract we should always override hashCode() method whenever we override equals() method. If not, what will happen? If we use hashtables in our application, it will not behave as expected. As the hashCode is used in determining the equality of values stored, it will not return the right corresponding value for a key.

Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it. This is the lowest form of equality implementation and provides guaranteed results for hastables implementation. When we override equals() and change the meaning of equality for an object then the same should be reflected by overriding the hashCode method.

May be you should also go through String equals also at this juncture as String equality is one of the celebrated topic in Java.

This Core Java tutorial was added on 16/06/2013.

«

»

Comments on "hashCode And equals Methods Override" Tutorial:

  1. Shivang Gupta says:

    I think there’s a typo here. Shouldn’t it be this.color.equals(tiger.getColor()) and this.stripePattern.equals(tiger.getStripePattern()) ?

    • Mohamed Galala says:

      Yes, exactly in the implementation example of overriding the Equals method.

    • Danny says:

      Override…..

    • Shiv says:

      Hi,
      Consider the below code.
      //Created Tiger class with only Height as member variable. Overridden only equals().
      public class Tiger
      {
      int height = 1;
      public Tiger(int height)
      {
      this.height = height;
      }

      @Override
      public boolean equals(Object obj)
      {
      Tiger other = (Tiger) obj;
      if (height != other.height)
      return false;
      return true;
      }
      }

      //In the main class: Created 2 tiger objects and added them to HashMap.
      Tiger t1 = new Tiger(1);
      Tiger t2 = new Tiger(2);

      Map tigerMap = new HashMap();
      tigerMap.put(t1, “1st Tiger”);
      tigerMap.put(t2, “2nd Tiger”);

      In the above code, both Tiger1 and Tiger2 will return the same hashcode, but have different values. So for the same hashcode, both tigers will be stored.
      Retrieving these objects will also work fine.

      In this scenario, I don’t have to override hashcode().. right??

  2. deepak says:

    Hi, I have 1 question, if equals method says two object are equal so if in any class I implement equals method and hashcode method to always return same value, will that class be singleton?

    Please confirm.

    Thanks
    Deepak

    • Sushil says:

      I don’t think so…

      as contract says if two objects are equal(), their hashcode() should also be same, but reverse is not true.

      Their could be 2 objects having same hashcode but they are not equal.

      Please anybody can further explain this.

      • Avinash Y N says:

        Hi Sushil,
        You might have got answer to this by now.

        Consider a simple example of 2 names say MALA and LAMA.

        Let’s define hashCode() as A=1, B=2 etc.
        So here both MALA and LAMA have hashCode of 27.
        Here hashCode is equal for both Names but actually they are not same names. Hence it is not necessary that even if hashCode are equal, Objects should be equal.

        • msk@gl.com says:

          Very nice explanation

        • prasune john says:

          Guys, if you understand the reason behind having the contract for hashcode to be same for two objects which satisfies equals, it would be pretty clear. A collection like HashMap which uses hashing algoritm stores the object in a specific fashion. i.e, all objects with same hashcode is stored in the same index in a linkedlist. So, for retreiving the object, the hashcode is used to find the index. If the contract fails (hash code is not equal for objects that are equal) then search method of HashMap fails.

      • kailashdas says:

        if u create two object of usedefined class. implement hashcode() . u will get two object whose equla() gives false , but hashcode() gives true.

    • Moiz says:

      Hi deepak,

      According to the singleton concept, all the object references returned by a singleton class points to one and the same object i.e. there hashcode must be same and all there reference comparison(by == operator) should result in TRUE boolean value.

      For ex: A and B are the reference to the object returned by a singleton class then it should satisfy the following conditions:
      1) a.hashCode() == b.hashCode() or a.equals(b)
      2) a == b

      • Manjunath says:

        In a singleton scenario we have no reason to override equals.. This will return the same instance as u can’t create a new from ur class. U should just access the instance created.

  3. Rajkumar says:

    very nice. Keep posting.

  4. Prasad says:

    Good article. Thank You!

  5. Muralidhar N says:

    Hi Joe, nice explanation with Bengal tigers. found a typo mistake here:”guaranteed results for hastables implementation.”

    Thank you.
    Muralidhar N

  6. Karthik says:

    Nice :-)

  7. sachin anthwal says:

    Please elaborate this equals() and hashCode()

  8. Tarun says:

    thanks very nice post it clear all my doubt

  9. pius ndugo says:

    great stuff !

  10. Ragav says:

    Very Nice… :) .. Keep rocking..

  11. Back To Java says:

    Hello Joe,

    Thank you very much I understood very clearly, few of my interviews I have been asked the same question but could not able to answer, Now I am clear on this. Thanks again, hoping more posts from yourend.

  12. sasi says:

    very nice…

  13. Vish says:

    Nice article

  14. Nikhil says:

    Hi Joe,
    If i override hashcode(), is it mandatory to override equals() and why or why not?

    • Anonymous says:

      no yeah, if u delete all the lines from the code. it will work… otherwise shutdown the system and watch movie on TV…

  15. Ankit Tripathi says:

    Whenever a null is passed as argument to equals, it must return false. Ex : bengalTiger1.equals(null) must return false.
    Though you mentioned this in your code.
    I think, you could have added this line while mentioning the properties of equals method.

  16. Shradha says:

    Hey Joe..
    very nice article ..it clears all my doubts

  17. Anonymous says:

    Wonderful Explanation, Joe!! :)

  18. javalearner says:

    Thank you so much for a simple write up which tells a lot!!

  19. Nitya says:

    What will happen if we will override hashcode and wont override equals?

  20. Bala says:

    Dear Joe,

    I tried above example program its working properly.
    i have query on that.
    i removed the hashcode() now also got same result
    then what is the purpose of override hashCode() above program
    please help me out on this doubt.

    • Avinash Y N says:

      Hi Bala,
      If you really want to experience the power of hashcode() method then, the best example would be to store the Tiger Objects as a key in hashMap Collection.

      Eg: map.put(<>, “Bengal Tiger 1″);
      map.put(<>, “Bengal Tiger 2″);

      Now try to retrieve the value of <> from map. It will return null if you are not overriding hashCode.
      Then try the same exercise by implementing hashCode method. You will get the proper value.

      Basically hashCode is a slot through which the compiler understands where to search for a particular object. If there is no hashCode then the Compiler will not know where to look for the object and hence returns null.

      • Avinash Y N says:

        In above comment means tiger Object.

        • Shivdas Yeske says:

          Tried above example with hashmap as you suggested but getting value from hashmap whether I implement hashcode() or not.

          • Pankaj says:

            Well Joe, I have been following your articles and they are excellent ones no doubt. But for this example, it is not giving the desired output when I don’t override hashcode() method.

            So, please can you add a few lines in your above code and show how hashmap would return null if I don’t override hashcode() method.

            Thanks Pankaj

      • amarshi says:

        Map map = new HashMap();
        map.put(bengalTiger1, “Tiger-1″);
        map.put(bengalTiger1, “Tiger-2″);
        System.out.println(“bengalTiger1 and bengalTiger2: “+ bengalTiger1.equals(bengalTiger2));

        this still returns true??????

      • Anonymous says:

        ArrayList list=new ArrayList();
        list.add(“Tiger”);
        System.out.println(list);

        Output will be print as Tiger. Is it correct Bala….

  21. Sandeep Swaminathan says:

    Nice article. Thanks. On a lighter side the example given here is logically wrong. Stripes on each tiger are unique. So your equals method will never be true :P Think like a programmer. Always logic :D

  22. Rajasekhar says:

    Scenario 1: If two objects are equal by equals(), then those two objects of hash code must be same.

    Scenario 2: If two objects are not equal by equals(),then those two objects of hash code may or may not same.

    Scenario 3: If two objects of hash code is same then those two objects are may or may not equal.

    Scenario 4: If two objects of hash code is not same,then those two objects must be different.

    Note: If am wrong in above case,please correct me.Thanks

  23. kuppumani says:

    good

  24. kumar says:

    can you please explain the logic in hashCode

    why the 3 and 7 values
    int hash = 3;
    hash = 7 * hash + this.color.hashCode();

    • Joe says:

      No special meaning to numerals 3 and 7. They are there just to show that, we can add our own logic there to calculate hash.

    • Alwin Jose M says:

      3 and 7 represent prime numbers. Instead of that, we can use any primitive numbers like 2, 3, 5, 7, 11, 13, 17 etc.,,

    • Alwin Jose M says:

      3 and 7 represent prime numbers. Instead of that, we can use any prime numbers like 2, 3, 5, 7, 11, 13, 17 etc.,,

  25. Mohamed says:

    Hats off man….!!!.. well taght :)

  26. Lathish says:

    very well explained…found the right place for java doubts.. :)

  27. Jaywant Patil says:

    JOE,
    Thanks, all concepts are very well explained…
    I always refer this site for any java related problems.

    Regards,
    Jaywant PATIL(Software Analyst)

  28. Anonymous says:

    hii i just wanted to know the contact’s name pls let me know ,

    thanks
    subha

  29. Prem Kumar says:

    Good article. Why are you keeping the tiger images on the blog. It is funny.

    • Joe says:

      Thanks Prem.

      I love animals. It has no significance with the technology and topic. But the code example has reference to siberian and bengal tiger. Just added this for fun, nothing official about it :-)

  30. Ashwani says:

    Nice JOE, very nice example. Its easy to understand….Thanks.

  31. Ashwani says:

    JOE, I have doubt – Logic made by us in overridden Hashcode() method can also generate similar hashcode value for 2 or more different objects. What will we do in that case??

  32. chander says:

    Easy to Understand, Thanks JOE.

  33. skynafo says:

    Thank you so much dude :)

  34. chandan mishra says:

    how to write overridden hashcode method

  35. Rahul Kamuni says:

    Superb explanation. Now I got it why we need to overide() equals and hashcode() method.

  36. raekwon says:

    Great explanation on this topic. Thanks for this awesome site and Keep up the good work!

  37. allen.ngorora@gmail.com says:

    Thanks it helps

  38. Yuvaraj Mani says:

    Came across your blog while writing some code. Very nice collection of java helps. Thanks for putting this blog up.

  39. madhusudhan says:

    public int hashCode() {
    int hash = 3;
    hash = 7 * hash + this.color.hashCode();
    hash = 7 * hash + this.stripePattern.hashCode();
    return hash;
    }

    why hash value is assigned to times(color.hashcodes and stripepattern.hashcode) anyway the resultnat hash value( return hash) will return only one hash value..

    please explain

    • Sri Harrsha says:

      It does return only one value as you know, but the function is just trying to generate a unique value using both of the field’s Hash Code value,Instead of depending on only one’s hashCode Value .

  40. Anonymous says:

    Very good explaination.

  41. Sandip says:

    suppose if we return same value each time from hascode() then what will happen?

  42. Anonymous says:

    thnks….

  43. Vinita says:

    Hi Joe,
    I have read many articles about equals & hashCode and this is the best. Simple and Excellent description.
    (though some more points could have been added, like is it mandatory to override equals if hashCode is overridden, etc)
    The tiger pictures is the best part. I will always remember these tigers whenever this concepts comes into my mind :)
    Thanks!

  44. srikanth says:

    My question is in which scenario both the methods will ovverride in strings or collections or some other area ??

  45. MICHELLE says:

    hi all

    in the article it seems like even though we not override a hashcode method for the class then while adding its object in to any collection
    use the class Object hashcode method.

    so Object hashcode method also give unique value and unlike the hashcode which we override to generate hashcode based on the alphabetial order of string for ex:MAY=hashcode’42’ and AMY=hashcod:’42’.

    it is fair to use Object’s hashcode() to avoid collision rather than overriding it in our own way?

  46. Md Farooq says:

    awesome explanation, i am very much thankfull for this article, keep posting

  47. Alwin Jose M says:

    I got good idea about equals and hashCode. Thanks all

  48. […] for all classes and have some list of functions same among them. I am referring to methods like hashCode(), clone(), toString() and methods for threading which is defined in Object […]

  49. Giridhar says:

    Nice explanation, I got good idea about equals() and hashcode() method. Thanks !

Your Comment

↑ Go to top