[At the time of this writing, three other answers were published.]
I repeat, the goal of my question is to find standard test cases to confirm that hashCode and equals agree with each other. My approach to this issue is to present the general paths used by programmers to write the classes in question, namely, immutable data. For example:
- Wrote
equals() without writing hashCode() . This often means that equality has been defined as meaning the equality of the fields of two copies. - Wrote
hashCode() without writing equals() . This may mean that the programmer was looking for a more efficient hash algorithm.
In case # 2, the problem seems insignificant to me. No additional instances were made by equals() , so no extra instances are required to obtain equal hash codes. In the worst case, a hashing algorithm may produce worse performance for hash cards, which is beyond the scope of this question.
In case # 1, the standard unit test entails creating two instances of the same object with the same data passed to the constructor, and checking for equal hash codes. What about false positives? You can select constructor parameters that simply result in equal hash codes on a nonetheless unfounded algorithm. A unit test, which seeks to avoid such parameters, will be in keeping with the spirit of this question. The shortcut here is to check the source code for equals() , ponder and write a test based on this, but in some cases it may be necessary, there may also be general tests that catch common problems - and such tests also fulfill the spirit of this question .
For example, if the test class (call it Data) has a constructor that takes a string, and instances built from strings that equals() get instances that were equals() , then a good test will probably check
new Data("foo")- another
new Data("foo")
We could even check the hash code for new Data(new String("foo")) to make String not be interned, although more likely to get the correct hash code than Data.equals() should give the correct result. in my opinion.
Eli Courtwright's answer is an example of how difficult it is to overcome a hash algorithm based on knowledge of the equals specification. An example of a special collection is a good one, as custom Collection sometimes appear and are very prone to errors in the hash algorithm.
Paul Brinkley Oct 10 '08 at 10:56
source share