• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Confusion with hashCode() and equals() method

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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())

 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Greenhorn
Posts: 10
Python Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic