wood burning stoves*
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


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark ".equals() and .hashcode()" Watch ".equals() and .hashcode()" New topic
Author

.equals() and .hashcode()

Jeff Gaer
Ranch Hand

Joined: Jun 04, 2001
Posts: 99
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
Rancher

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.
Dave.
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Oops, meant to post a link to the bunkhouse. There is a review of the book there.
Dave.
 
 
subject: .equals() and .hashcode()