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

标签 java android sorting arraylist

我有一个带有自定义对象的 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/

相关文章:

java - ParticleEffect Lib block 数据

Java 为什么默认的 Java 版本是 1.7,而不是 1.8

java - 使用 replace() 或 replaceall()

java - 保护连接检查 SSL 证书?

sorting - JSF2/Primefaces dataTable 排序不适用于 ViewScoped bean

Android 4.4.4 上的 java.lang.noClassDefFoundError,适用于 5.0+

android - 使用base64 encodein android将图像数据转换为字节码

android - 将应用程序置于后台并在 huawei mya-L22 上关闭屏幕时,GPS 位置更新停止更新

java - 多态排序转换

arrays - 如何根据 Aurelia/Typescript 中的嵌套属性对对象数组进行排序