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

.equals() and .hashcode()

Jeff Gaer
Ranch Hand

Joined: Jun 04, 2001
Posts: 103
Its recommended that IF you override equals() you over ride hashcode(). Why?
If code is not going to use hashtables, is it sufficient to do
public int hashcode(){return 1;}

If not, or if hashtables are required, what are some approaches that will meet all the requirements of equals? Or where would be a good place to read about this. I can guess some simple examples (i.e if its a string add the byte values of all chars in the string), but what about for more complex objects?
Where would be a good place to read more suggestions on approaches?

Sun Certified Java Programmer Java 2<P>Jeff Gaer
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Sounds like you should invest in Effective Java by Joshua Bloch (not a plug, I just finished reading a good coverage on this exact subject )
Basically the reason is that several APIs require two objects that are equal to return the same hash value. Another point is that the "return 1" code may be valid but seriously degrades the performace of hash codes.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Oops, meant to post a link to the bunkhouse. There is a review of the book there.
It is sorta covered in the JavaRanch Style Guide.
subject: .equals() and .hashcode()
It's not a secret anymore!