Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 否定比较链_Java_Comparison_Guava - Fatal编程技术网

Java 否定比较链

Java 否定比较链,java,comparison,guava,Java,Comparison,Guava,我写了这样的东西 @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(); } 为了颠倒顺序,我简单地否定了结果

我写了这样的东西

@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();
}
为了颠倒顺序,我简单地否定了结果,但现在我发现它是错误的,正如文档所说的那样

结束此比较链并返回其结果:具有 与链中第一个非零比较结果相同的符号,如果 每个结果都是零

因此
Integer.MIN_VALUE
是允许的返回值,然后求反失败。在源代码中,我可以看到除了-1、0和+1之外,没有任何东西会被返回,但这不是我想要依赖的东西


我可以交换所有操作数,而不是求反。简单难看,但我很好奇是否有更好的解决方案。

我不知道这是否更好(我个人不喜欢涉及浮点运算),但您可以通过以下方式发送:

我可能只是交换操作数。

也许是这样

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;

一个可能比反转
compare
参数更清楚的选项是将每对参数与其自然顺序相反的顺序进行比较:

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

实际上有一个signum函数不使用浮点,即
Integer#signum(int)
,它比
Math.signum
快约3.5倍,转换为
double


出于好奇,最快的解决方案是

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

但是只有大约10%。

在他们的
ReverseOrdering
类中,番石榴团队只是交换参数。Comparator.reverse()委托Collections.reverseOrder(Comparator),它返回一个只交换参数的比较器。因此,交换参数看起来是一种可行的方法,前提是您不能用Comparator.comparingInt(c->c.c0)替换CompariOnChain。然后再将comparingInt(c->c.c1)。reversed()并让JDK开发人员担心实现这一点的最佳方法。
return -((x&1) | (x>>1));