File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Overriding hashCode() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Overriding hashCode()" Watch "Overriding hashCode()" New topic
Author

Overriding hashCode()

Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228
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
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
If oid is a String, you can return its hashCode.
Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228
How does it Guarantee the hashCode() method returns same hashCode for two objects?
Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228
If the object equals() doesnt simply depend on oid and is more complex then how to implement it?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overriding hashCode()