• 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
  • Ron McLeod
  • Tim Cooke
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Jeanne Boyarsky
Saloon Keepers:
  • Stephan van Hulst
  • Carey Brown
  • Tim Holloway
  • Piet Souris
Bartenders:

Overriding hashCode()

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

I am overriding the equals() method of the object.
Example:
Class Blah
{
public abstract String getOid();
public boolean equals(Object o)
{
return this.getOid().equals(((Blah)o).getOid());
}
}
I assume If the oid's of the two classes are equal then the two objects are equal.
I read that its a best practice to override hashCode() method when you override equals() method and it should return the same hashCode if two objects are equal.
What should be the implementation for the hashCode() method?

Thanks in advance
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If oid is a String, you can return its hashCode.
 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How does it Guarantee the hashCode() method returns same hashCode for two objects?
 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If the object equals() doesnt simply depend on oid and is more complex then how to implement it?
 
Keith Lynn
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An efficient way would be to return the same hashCode every time.

But to make it more efficient, you would need to, depending on what makes the two objects equal, make sure the hashCodes are the same if the objects are equal.
 
Ew. You guys are ugly with a capital UG. Here, maybe this tiny ad can help:
The Low Tech Laboratory Movie Kickstarter is LIVE NOW!
https://www.kickstarter.com/projects/paulwheaton/low-tech
reply
    Bookmark Topic Watch Topic
  • New Topic