aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusion with hashCode() and equals() method Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Confusion with hashCode() and equals() method" Watch "Confusion with hashCode() and equals() method" New topic
Author

Confusion with hashCode() and equals() method

jami siva
Ranch Hand

Joined: Oct 16, 2009
Posts: 56
Hi,

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

Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3011
    
    9
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.


Joanne
Devendra Mahra
Greenhorn

Joined: Jul 17, 2011
Posts: 10

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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Confusion with hashCode() and equals() method
 
Similar Threads
Which is best to use in hashcode?
Custom Search With ArrayList
Comparator doubt
Eclipse equals and hashcode
Using the equals and Hashcode methods of an Object?