When i try to run the below program with out the hashCode() but equals(), I am getting output as null.
But i tried to run with hashCode() and equals() method, I am getting the proper value(means in this case Feb).
I know equals() method will do object comparision( in this case by using name). But using equals() alone why I am not getting the proper value.
I analysed the below one like this. If we were not implemented hashCode(), default hashCode() method will call and store all objects in one single bucket in that it invokes equals method to find correct object.
After reading all the things from K&B, I got confused over all. Can any one explain this briefly?(when to implement equals() and when to implement hashCode())
jami siva wrote:default hashCode() method will call and store all objects in one single bucket
The exact opposite actually. The default implementation of hashCode does it's best to return distinct integers for distinct objects. Therefore if you don't override hashCode, the Friend instance you created in line 6 will more than likely have a different hashCode value to the Friend instance you created in line 8 and cannot be therefore considered equal by anything that uses the hashCode.
You need to override hashcode method whenever equals method is overridden. This is to make sure that contract for the hashCode method is intact, which states that equal objects must have equal hash codes. The default hashcode method will not guarantee that two equal Friend objects will have same hashcode.