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.

+3


source to share


4 answers


There is actually a signum function that does not have a floating point, namely Integer#signum(int)

, and it is about 3.5 times faster than Math.signum

casting to double

.


Out of curiosity, the quickest solution is



return -((x&1) | (x>>1));

      

but only about 10%.

0


source


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.

+1


source


Maybe this?

int temp = ComparisonChain.start()
            .compare(this.d0, that.d0)
            .compare(this.d1, that.d1)
            .compare(this.d2, that.d2)
            .result();

return temp == Integer.MIN_VALUE ? Integer.MAX_VALUE : -temp;

      

0


source


One option, which may be clearer than changing the arguments compare

, is to compare each pair of arguments with the reverse of their natural ordering:

.compare(this.d0, that.d0, Ordering.natural().reverse())

      

0


source







All Articles