maaartinus
maaartinus

Reputation: 46472

Negate comparison chain

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 simply negated the result, but now I see it was wrong as the docs says

Ends this comparison chain and returns its result: a value having the same sign as the first nonzero comparison result in the chain, or zero if every result was zero.

So Integer.MIN_VALUE is an allowed return value and then the negation fails. In the source code, I can see that nothing but -1, 0, and +1 gets ever returned, but this isn't something I'd like to depend on.

Instead of the negation I could swap all the operands. Simple and ugly, but I'm curious if there's a better solution.

Upvotes: 5

Views: 1488

Answers (4)

maaartinus
maaartinus

Reputation: 46472

There's actually a signum function using no floating point, namely Integer#signum(int) and it's about 3.5 times faster then Math.signum with the cast to double.


Out of curiosity, the fastest solution is

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

but only by about 10%.

Upvotes: 0

ColinD
ColinD

Reputation: 110054

One option that may be more clear than reversing the compare arguments would be to compare each pair of arguments with the reverse of their natural ordering:

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

Upvotes: 4

Xabster
Xabster

Reputation: 3720

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;

Upvotes: 0

Thilo
Thilo

Reputation: 262684

I don't know if that's better (personally I don't like to involve floating point operations), but you could send it through Math#signum:

return -Math.signum( .... );

I'd probably just swap the operands.

Upvotes: 1

Related Questions