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,
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.
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
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,
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 are closed for "hashCode And equals Methods Override".
I think there’s a typo here. Shouldn’t it be this.color.equals(tiger.getColor()) and this.stripePattern.equals(tiger.getStripePattern()) ?
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
very nice. Keep posting.
Yes, exactly in the implementation example of overriding the Equals method.
Good article. Thank You!
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.
Override…..
Hi Joe, nice explanation with Bengal tigers. found a typo mistake here:”guaranteed results for hastables implementation.”
Thank you.
Muralidhar N
Nice :-)
Please elaborate this equals() and hashCode()
thanks very nice post it clear all my doubt
great stuff !
Very Nice… :) .. Keep rocking..
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.
very nice…
Nice article
Hi Joe,
If i override hashcode(), is it mandatory to override equals() and why or why not?
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.
Hey Joe..
very nice article ..it clears all my doubts
Thank you so much for a simple write up which tells a lot!!
What will happen if we will override hashcode and wont override equals?
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.
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.
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.
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
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
good
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.
Hats off man….!!!.. well taght :)
very well explained…found the right place for java doubts.. :)
JOE,
Thanks, all concepts are very well explained…
I always refer this site for any java related problems.
Regards,
Jaywant PATIL(Software Analyst)
bengalTiger1.equals(null) will not return false. it will throw NullpointerException.
hii i just wanted to know the contact’s name pls let me know ,
thanks
subha
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 :-)
Thanks Jaywant. Enjoy!
Nice JOE, very nice example. Its easy to understand….Thanks.
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??
Easy to Understand, Thanks JOE.
if u create two object of usedefined class. implement hashcode() . u will get two object whose equla() gives false , but hashcode() gives true.
Thank you so much dude :)
Tried above example with hashmap as you suggested but getting value from hashmap whether I implement hashcode() or not.
how to write overridden hashcode method
Superb explanation. Now I got it why we need to overide() equals and hashcode() method.
Great explanation on this topic. Thanks for this awesome site and Keep up the good work!
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
Thanks it helps
Came across your blog while writing some code. Very nice collection of java helps. Thanks for putting this blog up.
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.
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
Very good explaination.
suppose if we return same value each time from hascode() then what will happen?
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??????
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 .
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??
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!
My question is in which scenario both the methods will ovverride in strings or collections or some other area ??
superbbbb………
no yeah, if u delete all the lines from the code. it will work… otherwise shutdown the system and watch movie on TV…
ArrayList list=new ArrayList();
list.add(“Tiger”);
System.out.println(list);
Output will be print as Tiger. Is it correct Bala….
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?
@Arvind It will give as false not NPE
how come Tiger1 and Tiger2 returns same hashcode?
awesome explanation, i am very much thankfull for this article, keep posting
hascode() method will return different values.
Are you meant the map’s key values as the reference of the Tiger objects
3 and 7 represent prime numbers. Instead of that, we can use any prime numbers like 2, 3, 5, 7, 11, 13, 17 etc.,,
I got good idea about equals and hashCode. Thanks all
[…] 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 […]
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.
Nice explanation, I got good idea about equals() and hashcode() method. Thanks !
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