r/ProgrammerTIL • u/TangerineX • Feb 14 '18
Other [Java] Never use HashCode to implement compareTo
Deterministic randomness is a crucial feature of the product that I'm working on. We were investigating possible sources of non-determinism, and I came across a class that implemented Comparable and used HashCode. The code looked somewhat like this
@Override
public int compareTo(Foo o) {
if (hashCode() < o.hashCode()) {
return -1;
}
if (hashCode() > o.hashCode()) {
return 1;
}
return 0;
}This was implemented because wanted to make sure that these objects were put in some deterministic order, but did not care too much about what order it was in.
It turns out that the default implementation of hashCode depends on your JVM, and generally uses the memory address. The memory address is assigned by the JVM internally and will have no correlation with your random seed. Thus, the sort was effectively random.
On a related note, the default implementation of toString can potentially use the memory address as well. When implementing compareTo, always use a piece of information that is deterministic and intrinsic to the object, even if you don't care about the sorted order.
23
u/mctwistr Feb 14 '18
I can't even begin to understand why hashCode() would ever be considered for this purpose by anyone... Even disregarding your comments about memory addresses, hash collisions for non-equivalent objects are an expectation and should therefore never be used for equality comparisons (returning 0 in your example).
5
u/rotharius Feb 14 '18
Thanks for the warning. Hash code is used for in-memory referencing, such as HashMaps.
More deterministic would be to use an actual hash function like an md5, sha or even a uuidv5 based on the properties (or serialization) of the object.
As an aside, if properties are allowed to change over time (as is the case for entities), a more non-deterministic, less collision-prone method should be chosen (e.g. uuidv4) for identifying a single entity.
4
u/GiantRobotTRex Feb 14 '18 edited Feb 14 '18
If I've overridden equals(), then I'm going to override hashCode() – it's required by the Java specifications. So if I don't care about persistent sorting across runs, then the only problem with your code is when a hash collisions occurs, but that can be entirely avoided for some classes.
8
u/[deleted] Feb 14 '18
The hash code... uses memory address? What possible reason could there have been to think that was a good idea? What madman at Sun thought that nondeterministic hashing was even tolerable?
2
u/[deleted] Feb 14 '18
Also hashCode() returns an int (32bit), and a 64bit system has 45 or 46 significant bits per address (48bits per address, -2 or -3 bits alignment), so you'd need to take care of clashes.
1
u/BoobDetective Feb 14 '18
I thought one was expected to overwrite the hashcode function for his/her class implementation. At least that was what I was taught at the first year of CS.