Comparison chain of negative values
I wrote something like
@Override public int compareTo(Cuboid that) {
return -ComparisonChain.start()
.compare(this.d0, that.d0)
.compare(this.d1, that.d1)
.compare(this.d2, that.d2)
.result();
}
To reverse the order, I just denied the result, but now I see it was wrong as the docs say
Ends this comparison chain and returns its result: a value that has the same sign as the first non-zero comparison result in the chain, or zero if each result is zero.
So Integer.MIN_VALUE
- is a valid return value and then no negation is done. In the original code, I see that nothing but -1, 0 and +1 is ever returned, but that is not what I would like to depend on.
Instead of negating, I could swap all the operands. Simple and ugly, but I'm curious if there is a better solution.
source to share
I don't know if it was any better (I personally don't like floating point operations), but you can send it via Math # signum :
return -Math.signum( .... );
I would just change the operands.
source to share