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?

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;

}
}

```

Example Code Output:

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

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.

previous post: Show Map in Android

next post: Iterator Design Pattern

71 comments on “hashCode And equals Methods Override”

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

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

• 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??

• Very good questions.

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

Thanks
Deepak

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

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

• Very nice explanation

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

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

• 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

3. very nice. Keep posting.

4. Good article. Thank You!

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

Thank you.
Muralidhar N

6. Please elaborate this equals() and hashCode()

7. Very Nice… :) .. Keep rocking..

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

• superbbbb………

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

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

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

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

• @Arvind It will give as false not NPE

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

12. Wonderful Explanation, Joe!! :)

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

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

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

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

• In above comment means tiger Object.

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

• 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??????

• ArrayList list=new ArrayList();
System.out.println(list);

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

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

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

18. can you please explain the logic in hashCode

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

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

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

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

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

Regards,
Jaywant PATIL(Software Analyst)

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

thanks
subha

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

• 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 :-)

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

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

26. Easy to Understand, Thanks JOE.

27. Thank you so much dude :)

28. how to write overridden hashcode method

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

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

31. Thanks it helps

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

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

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

34. Very good explaination.

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

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

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

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