3 ms·
Even general purpose programming languages have this. Java has at least 4 as well: * Assignment (=) * Referential equality (==) * Structural equality (.equal
by gizmo686 2y ago
Even general purpose programming languages have this. Java has at least 4 as well:
* Assignment (=)
* Referential equality (==)
* Structural equality (.equals())
* Comparison equality (.compareTo(_) == 0 )
- auggierose 2y ago.equals() and .compareTo(_) == 0 are required to be the same. If you program it differently, it is a bug.
- gizmo686 2y agoFrom the javadoc: > It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
- auggierose 2y agoNice catch. Now you also found buggy documentation / specification!
- xboxnolifes 2y agoWhy is it buggy?
- auggierose 2y agoWhy would you allow .equals and .compareTo to have inconsistent meanings? That is a guaranteed source of bugs. I cannot think of a single good reason to allow this. If you need a different order for some reason, that is what the Comparator interface is for.
- maxbond 2y agoIf it's a bad idea but considered legal according to the documentation, then that would make it a footgun rather than a bug, no?
- auggierose 2y agoYes, that makes this a footgun, and the specification containing this footgun buggy. It is a bug in the spec because there is no good reason for the footgun being there.
- maxbond 2y agoYou have not yet imagined a reason, and neither have I. That doesn't mean one doesn't exist. Likely it would be something idiosyncratic involving legacy code that would only make sense in a real world context - "we have to change the way it sorts to fix ticket ABC123, but we can't change the equality, or we'll have a regression of ABC456."
- auggierose 2y agoThen provide a comparator to sort differently, no problem. There will never be a good reason for the spec to be like that. Just look how people here justify the mess of BigDecimal.
- myrryr 2y agoThings where equality is on more than one axis, _but there is a primary one where people use._ Think things like vectors or complex numbers, or people. The absolutely classic example however is types which have a signed zero...
- auggierose 2y agoThat is not a problem, just pick the same equality that your .compareTo method uses. You could pick -0 < 0, and -0 ≠ 0, or -0 = 0. You should never pick -0 < 0 (via compareTo), but -0 = 0 (via equals).
- maple3142 2y agoHmm, there was an article about Java's BigDecimal behaves differently for equals and compareTo: https://igorstechnoclub.com/java-bigdecimal/ https://igorstechnoclub.com/java-bigdecimal/
- auggierose 2y agoThat is a great example why I consider the spec buggy. With a proper spec, stuff like that would not fly from the start.