Re: hashCode() for Custom classes
sasuke wrote:
Hello to all Java programmers out there.
I am currently faced with the task of providing a logical equals()
method for my domain / business classes. This job being done, I now
have to override the hashCode() so that when an object of this class
is used as a key in a Map, the Map behavior is well defined.
I have thought of a couple of ways to do this but would like to give
inputs on my thoughts:
One thing nobody else has mentioned so far (at least I think not -- this
thread is long and I may have missed it) is that when combining, sometimes
it may be best to leave out the hash code of some of the members.
The whole point of hashCode() is performance. At some point, the hash
code is good enough to avoid most collisions, and making the collision
rate 0.1% better but making hashCode() take twice as long to run is not
a good trade-off.
So, suppose you have class M containing members that are instances
of classes A, B, C, D, and E. Sometimes this:
int hashCode() {
return a.hashCode() + b.hashCode() + c.hashCode();
}
might be a better implementation than this:
int hashCode() {
return a.hashCode() + b.hashCode() + c.hashCode()
+ d.hashCode() + e.hashCode();
}
This could be particularly true if, say, instances of D tend to
contain a really long string.
Another thing to consider is that perhaps the value of one member
is actually dependent on (or derived from) a value of another.
For example, suppose I have this class:
class Foo {
private final File file;
private final String displayName;
Foo (File file) {
this.file = file;
this.displayName = file.getName();
}
int hashCode() {
return file.hashCode() + displayName.hashCode();
}
}
There is really no point in Foo.hashCode() bothering with the call to
displayName.hashCode(). All the information in displayName came
from file, so there is nothing additional for it to contribute.
- Logan