• 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:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Regarding Overriding Of equals() and hashcode()

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

It would be very great if any body gives detail explanation why we need to
override hashcode(), if we override equals() or vice verse?

Thanks in advance.


Thanks and Regards,
Gopal Potluri
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Gopal

If you override equals so that 2 objects appear equal but they have different hashcodes then when you put them in a Set Collection (which should never contain duplicates) they may both get put in.

This is because the Set uses the hashcode to put the object in a 'bucket'. It then uses the hashcode of another object to check if an object like that is already in the set.

But if your 2 objects, which your equals() says are the same, end up in different buckets, then the set will wrongly contain them both.

So when changing equals() you have to change hashcode so that two equal objects have the same hashcode.

Hope that helps

Wyn
 
V. Potluri
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Wyn Riley ,

Thanks for clearing my doubt. I am very thankful for spending your precious time to clear my doubt.

Regards,
Gopal P.
 
money grubbing section goes here:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic