Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

.equals() and .hashcode()

 
Jeff Gaer
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops, meant to post a link to the bunkhouse. There is a review of the book there.
Dave.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic