3 ms·
It is perfectly reasonable to want all sorted collections of X to have a canonical order, but to still allow people to consider equivalent items to be equal. T
by tsimionescu 2y ago
It is perfectly reasonable to want all sorted collections of X to have a canonical order, but to still allow people to consider equivalent items to be equal.
The example someone else gives with +0 and -0 is very good: in most contexts, those two should probably be equal (+0.equals(-0)), but when sorting a list, you might want all -0s to come before all +0s (-0.compareTo(+0) == -1).
Given that Comparable is almost exclusively used for sorting, this is actually quite unlikely to cause problems in practice.
Of course, it's a much bigger problem if you use entirely different concepts of equality. For example, a Name class where a.equals(b) only if they have the exact same Unicode code points, but where a.compareTo(b) == 0 if they have the same Unicode codepoints after normalization would be crazy.
Edit: and of course BigDecimal from the example below does exactly this crazy thing...
- auggierose 2y agoYep, BigDecimal does this crazy thing, and it shouldn't. It does it, because the buggy spec allows it. If the canonical equality you want to provide is not compatible with the canonical order you want to provide, then don't provide the canonical order. Or provide an order that is compatible, which makes it pretty much canonical. It is really simple, and going against simple things like that is why software is such a mess. Because software really allows you to do anything you want. And now it is down to you to want the right thing.