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.
View all comments
Show parent comment
6
u/Hikaru755 Feb 14 '18 edited Feb 14 '18
Look at the requirements for the hashcode method in Java:
This method was only ever meant for efficiently comparing object references at runtime, for example for looking them up in a HashMap. It's not meant to be used outside of a running program, for a checksum mechanism or anything like that. And with that in mind, using the memory address is a fair solution - it guarantees that the same object reference always returns the same hashcode, that two different objects will most likely have different hashcodes, and therefore that hashcode is consistent with equals for objects that override neither. Any other way to do this would involve keeping track of random numbers associated with objects, or actually introspecting the object properties, which could cause lots of headaches and undesired side effects.