I see I missed one part of the contract and also failed to see the reason why HashMap.comparableClassFor
exists.
The contract says
(x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0
so whenever there's an X
greater than a Y
and a Y
greater than an X
, then the two instances of X
must be comparable to each other. This doesn't leave much freedom:
- Either one of the types is empty. This makes no sense at all.
- Or all instances of
X
are smaller or equal to all instances ofY
(or the other way round). This is slightly less nonsensical.
So, I'm concluding that it's possible, but makes no sense. The simplest example is
class X implements Comparable<Void> {
public int compareTo(Void v) {
return 43; // or throw or whatever, it doesn't matter
}
}
I guess that the reason for HashMap.comparableClassFor
is to support different implementations of a common superclass like
abstract class AByteArray implements Comparable<AByteArray> {}
class SparseByteArray extends AByteArray {...}
class DenseByteArray extends AByteArray {...}
This seems to make sense and can be even consistent with equals.