我们的一些用户在对列表进行排序时遇到此异常。抛出它的代码是
Collections.sort(activeConverstions, new Comparator<Conversation>() {
@Override
public int compare(Conversation o1, Conversation o2) {
return (int)(o2.getTime()- o1.getTime()); // descending order
}
});
虽然 getTime() 是“long”类型
最佳答案
问题可能是将 long
转换为 int
,这可能会将较大的 long
数字转换为负数 int
.
例如,考虑这个 fragment :
long first = Integer.MAX_VALUE + 1;
long second = 0;
System.out.println((int) (first - second));
System.out.println((int) (second - first));
输出:
-2147483648
-2147483648
如果您要将两个 Conversation
实例传递给您的 compare
方法 - 让我们称它们为 x
和 y
-其getTime()
分别等于上面代码段中的first
和second
,两者都是compare(x,y)
和 compare(y,x)
将返回一个负值,这违反了该方法的约定。
尝试:
Collections.sort(activeConverstions, new Comparator<Conversation>() {
@Override
public int compare(Conversation o1, Conversation o2) {
return o2.getTime() > o1.getTime() ? 1 : o2.getTime() < o1.getTime() ? -1 : 0;
}
});
或者,如 assylias 所建议的那样:
Collections.sort(activeConverstions, new Comparator<Conversation>() {
@Override
public int compare(Conversation o1, Conversation o2) {
return Long.compare(o2,getTime(), o1.getTime());
}
});
关于java - Collections.sort - IllegalArgumentException : Comparison method violates its general contract,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38996395/