问题描述
我有一个带有自定义对象的ArrayList.它们包含一个我想对其进行排序的复选框对象.我正在使用此比较器函数对其进行排序:
I have an ArrayList with custom objects. They contain a checkbox object that I want to sort on. I am using this comparator function to sort it:
我正在使用XOR运算符检查彼此是否相等,然后取反.
I am using the XOR operator to check if they are equal to each other, then negate it.
但是这不起作用,并且列表保持相同的顺序.
However this is not working, and the list is staying in the same order.
有人知道怎么了吗?
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(等于).
You return only -1 (less than) or +1 (greater than), never 0 (equals to).
在前面的描述中,符号sgn(expression)表示 数学符号函数,其定义为返回以下值之一 根据表达式的值是负数,零值还是正数,分别为-1、0或1.
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.
实施者必须确保sgn(compare(x,y))== -sgn(compare(y, x))对于所有x和y. (这意味着compare(x,y)必须抛出一个 并且仅当compare(y,x)引发异常时才发生异常.)
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.)
实现者还必须确保该关系是可传递的: (((compare(x,y)> 0)&&(compare(y,z)> 0))表示compare(x,z)> 0.
The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
最后,实现者必须确保compare(x,y)== 0意味着 所有z的sgn(compare(x,z))== sgn(compare(y,z)).
Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
通常是这种情况,但并非严格要求(compare(x, y)== 0)==(x.equals(y)).一般来说,任何比较器 违反此条件应清楚地表明这一事实.这 推荐的语言是注意:此比较器强加了以下命令: 与等式不一致."
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之前的提案:
Proposal before 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;
}
提案从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中使用布尔值对ArrayList进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!