5

java7有排序问题吗?我正在使用 Collections.sort(list, 比较器)

当我切换到 java7 时,我注意到排序结果与我使用 java6 时的结果不同。

示例:列表 = [d, e, b, a, c, f, g, h]

在 java6 Collections.sort(List,comparator) 导致 [a, b, c, d, e, f, g, h]

在 java7 Collections.sort(List,comparator) 导致 [b, a, c, d, e, f, g, h]

列表中的前两个值已交换。

4

2 回答 2

9

Java 7 从Merge 排序切换到Tim 排序它可能会导致“损坏的比较器”的顺序发生轻微变化(引用Arrays源代码中的注释):

/**
 * Old merge sort implementation can be selected (for
 * compatibility with broken comparators) using a system property.
 * Cannot be a static boolean in the enclosing class due to
 * circular dependencies. To be removed in a future release.
 */

尝试使用以下命令运行 JVM:

java -Djava.util.Arrays.useLegacyMergeSort=true

目前尚不清楚“损坏的比较器”是什么意思,但显然它会导致排序数组中元素的不同顺序。

于 2012-12-07T18:37:52.083 回答
0

需要注意的一件事是,这可能会引起混乱。Collections.sort 是一种稳定的排序。这意味着对于相等的元素,它会保持它们原来的顺序,所以:

如果 a == b,那么

Collections.sort([d, e, b, a, c, f, g, h]) = [b, a, c, d, e, f, g, h]

Collections.sort([d, e, a, b, c, f, g, h]) = [a, b, c, d, e, f, g, h]

在我看来,这可能是您所看到的,或者有问题的比较器(或被排序的对象的自然顺序)没有按照您期望的方式工作。

于 2012-12-07T18:48:17.333 回答