gpt4 book ai didi

java - 如何在 java 中使用 boolean 值对 ArrayLists 进行排序?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:53:44 25 4
gpt4 key购买 nike

我有一个带有自定义对象的 ArrayList。它们包含一个我想要排序的复选框对象。我正在使用这个比较器函数对其进行排序:

我正在使用 XOR 运算符来检查它们是否彼此相等,然后取反。

但是这不起作用,列表保持相同的顺序。

有人知道怎么回事吗?

public class CustomSelectSort implements Comparator<ObjPerson> {
@Override
public int compare(ObjPerson o1, ObjPerson o2) {
return !(o1.select.isChecked() ^ o2.select.isChecked()) ? 1 : -1;
}
}

最佳答案

您只返回 -1(小于)或 +1(大于),从不返回 0(等于)。

参见 java.util.Comparator definition :

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.

It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."

Java 1.7之前的建议:

public int compare(ObjPerson o1, ObjPerson o2) {
boolean b1 = o1.select.isChecked();
boolean b2 = o2.select.isChecked();
if( b1 && ! b2 ) {
return +1;
}
if( ! b1 && b2 ) {
return -1;
}
return 0;
}

提案 since Java 1.7 :

public int compare(ObjPerson o1, ObjPerson o2) {
boolean b1 = o1.select.isChecked();
boolean b2 = o2.select.isChecked();
return Boolean.compare( b1, b2 );
}

关于java - 如何在 java 中使用 boolean 值对 ArrayLists 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18434028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com