Recently I read through this Developer Works Document.
The document is all about defining hashCode()
and equals()
effectively and correctly, however I am not able to figure out why we need to override these two methods.
How can I take the decision to implement these methods efficiently?
Test Class
In Object Class equals(Object obj) is used to compare address comparesion thats why when in Test class if you compare two objects then equals method giving false but when we override hashcode() the it can compare content and give proper result.
The reason behind this: When your object fields can be null, implementing Object.equals can be a pain, because you have to check separately for null. Using Objects.equal lets you perform equals checks in a null-sensitive way, without risking a NullPointerException.
Objects.equal("a", "a"); // returns true Objects.equal(null, "a"); // returns false Objects.equal("a", null); // returns false Objects.equal(null, null); // returns true
I was looking into the explanation " If you only override hashCode then when you call
myMap.put(first,someValue)
it takes first, calculates its hashCode and stores it in a given bucket. Then when you callmyMap.put(first,someOtherValue)
it should replace first with second as per the Map Documentation because they are equal (according to our definition)." :I think 2nd time when we are adding in
myMap
then it should be the 'second' object likemyMap.put(second,someOtherValue)
Because if you do not override them you will be use the default implentation in Object.
Given that instance equality and hascode values generally require knowledge of what makes up an object they generally will need to be redefined in your class to have any tangible meaning.
When you want to store and retrieve your custom object as a key in Map, then you should always override equals and hashCode in your custom Object . Eg:
Here p1 & p2 will consider as only one object and
map
size will be only 1 because they are equal.Consider collection of balls in a bucket all in black color. Your Job is to color those balls as follows and use it for appropriate game,
For Tennis - Yellow, Red. For Cricket - White
Now bucket has balls in three colors Yellow, Red and White. And that now you did the coloring Only you know which color is for which game.
Coloring the balls - Hashing. Choosing the ball for game - Equals.
If you did the coloring and some one chooses the ball for either cricket or tennis they wont mind the color!!!