hashCode And equals Methods Override

Last modified on November 8th, 2014 by Joe.

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,

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,

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,

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.

Comments on "hashCode And equals Methods Override"

  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()) ?

  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

  3. Rajkumar says:

    very nice. Keep posting.

  4. Mohamed Galala says:

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

  5. Prasad says:

    Good article. Thank You!

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

  7. Danny says:

    Override…..

  8. Muralidhar N says:

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

    Thank you.
    Muralidhar N

  9. Karthik says:

    Nice :-)

  10. sachin anthwal says:

    Please elaborate this equals() and hashCode()

  11. Tarun says:

    thanks very nice post it clear all my doubt

  12. pius ndugo says:

    great stuff !

  13. Ragav says:

    Very Nice… :) .. Keep rocking..

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

  15. sasi says:

    very nice…

  16. Vish says:

    Nice article

  17. Nikhil says:

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

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

  19. Shradha says:

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

  20. javalearner says:

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

  21. Nitya says:

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

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

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

  24. Avinash Y N says:

    In above comment means tiger Object.

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

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

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

  28. kuppumani says:

    good

  29. 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();

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

  31. Mohamed says:

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

  32. Lathish says:

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

  33. 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)

  34. Arvind says:

    bengalTiger1.equals(null) will not return false. it will throw NullpointerException.

  35. Anonymous says:

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

    thanks
    subha

  36. Prem Kumar says:

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

  37. 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 :-)

  38. Joe says:

    Thanks Jaywant. Enjoy!

  39. Ashwani says:

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

  40. 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??

  41. chander says:

    Easy to Understand, Thanks JOE.

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

  43. skynafo says:

    Thank you so much dude :)

  44. Shivdas Yeske says:

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

  45. chandan mishra says:

    how to write overridden hashcode method

  46. Rahul Kamuni says:

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

  47. raekwon says:

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

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

  49. allen.ngorora@gmail.com says:

    Thanks it helps

  50. Yuvaraj Mani says:

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

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

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

  53. Anonymous says:

    Very good explaination.

  54. Sandip says:

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

  55. 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??????

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

  57. 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??

  58. 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!

  59. srikanth says:

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

  60. Anonymous says:

    superbbbb………

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

  62. Anonymous says:

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

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

  63. 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?

  64. tribhuvan says:

    @Arvind It will give as false not NPE

  65. Anonymous says:

    how come Tiger1 and Tiger2 returns same hashcode?

  66. Md Farooq says:

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

  67. Alwin Jose says:

    hascode() method will return different values.

  68. Anonymous says:

    Are you meant the map’s key values as the reference of the Tiger objects

  69. 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.,,

  70. Alwin Jose M says:

    I got good idea about equals and hashCode. Thanks all

  71. […] 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 […]

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

  73. Giridhar says:

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

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

Comments are closed for "hashCode And equals Methods Override".