我最近遇到了一个表面看起来不正确的比较器.但是,我一直无法得到一个输入,导致比较器产生错误的结果.
如果o1 <= o2,它会错误地将值视为相等,如果o1> o2则正确返回1.
我试图在下面尽可能地简化场景.任何人都可以:
我已经尝试了很多,我正在扯皮!
package comparator;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class BadComparator implements Comparator<Integer>
{
public int compare(Integer o1, Integer o2)
{
// Generally Accepted implementation
//return o1 - o2;
// Incorrect(?) Implementation
return (o2 < o1) ? 1 : 0;
}
public static void main(String[] args)
{
List<Integer> intList = Arrays.asList(10, 9, 8, 1, 2, 3, 7, 4, 5, 6);
Collections.sort(intList, new BadComparator());
System.out.println(intList);
}
}
Run Code Online (Sandbox Code Playgroud)
它对我不起作用.它产生的输出:
[10, 9, 8, 1, 2, 3, 7, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
(与输入顺序相同).但这并不能保证......我怀疑它恰好选择了已经按正确顺序排列的元素,或者它决定它们"相等"并让它们孤立无援.
请注意,o1 - o2是也打破......考虑是否o1 = Integer.MIN_VALUE和o2 = 1......你能解决这个问题通过转换为long价值第一,当然.
一个更自然的实现方式
return o1.compareTo(o2);
Run Code Online (Sandbox Code Playgroud)
要么:
int i1 = o1.intValue();
int i2 = o2.intValue();
return i1 < i2 ? -1 : i1 == i2 ? 0 : 1;
Run Code Online (Sandbox Code Playgroud)