• Post Reply Bookmark Topic Watch Topic
  • New Topic

equals() and hashCode()  RSS feed

 
Tony Bateman
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm not sure what forum this belongs in, becasue this is only my second post; please move if inappropriate.

I have been looking at the collections classes and have a few questions:

1) equals() does not *have* to be overridden in your class, but if you don't the test is for absolute equivalence of the same object in memory, and not semantic equivalence, correct?

2) I assume that the same is true with hashCode(); if that is the case, how do you know if the default hashcode algorithm is "good enough"? Can you profile the performance of the algorithm?

3) Are there any guidelines that don't require a PhD to construct an appropriate hashcode algorithm for any arbitrary object?

Kind regards,

Tony.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) Correct.

2) The default is fine if you are using the default equals(), but if you override one, you must override the other, or hash-based containers won't work correctly.

3) There's an easy, useable recipe on page 38 of Josh Bloch's "Effective Java" which can be applied to almost any situation. This is a good book, well worth owning.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!