[At the time of this writing, three other answers were posted.]
To reiterate, the aim of my question is to find standard cases of tests to confirm that hashCode
and equals
are agreeing with each other. My approach to this question is to imagine the common paths taken by programmers when writing the classes in question, namely, immutable data. For example:
- Wrote
equals()
without writing hashCode()
. This often means equality was defined to mean equality of the fields of two instances.
- Wrote
hashCode()
without writing equals()
. This may mean the programmer was seeking a more efficient hashing algorithm.
In the case of #2, the problem seems nonexistent to me. No additional instances have been made equals()
, so no additional instances are required to have equal hash codes. At worst, the hash algorithm may yield poorer performance for hash maps, which is outside the scope of this question.
In the case of #1, the standard unit test entails creating two instances of the same object with the same data passed to the constructor, and verifying equal hash codes. What about false positives? It's possible to pick constructor parameters that just happen to yield equal hash codes on a nonetheless unsound algorithm. A unit test that tends to avoid such parameters would fulfill the spirit of this question. The shortcut here is to inspect the source code for equals()
, think hard, and write a test based on that, but while this may be necessary in some cases, there may also be common tests that catch common problems - and such tests also fulfill the spirit of this question.
For example, if the class to be tested (call it Data) has a constructor that takes a String, and instances constructed from Strings that are equals()
yielded instances that were equals()
, then a good test would probably test:
new Data("foo")
- another
new Data("foo")
We could even check the hash code for new Data(new String("foo"))
, to force the String to not be interned, although that's more likely to yield a correct hash code than Data.equals()
is to yield a correct result, in my opinion.
Eli Courtwright's answer is an example of thinking hard of a way to break the hash algorithm based on knowledge of the equals
specification. The example of a special collection is a good one, as user-made Collection
s do turn up at times, and are quite prone to muckups in the hash algorithm.