【问题标题】:Collections.sort() issue in java7java7 中的 Collections.sort() 问题
【发布时间】:2012-12-07 18:29:18
【问题描述】:

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, compare) 导致 [b, a, c, d, e, f, g, h]

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

【问题讨论】:

  • 向 oracle 报告错误..
  • Collections.sort 似乎不太可能被破坏。您观察到此结果的实际数据是什么(如图所示的字符或字符串数​​组)?您是否将 Comparator 传递给它?
  • 如果您可以展示一个具有此结果的示例代码,最好看看可能是什么问题
  • 显示比较器的代码

标签: sorting collections java-7


【解决方案1】:

Java 7 从 Merge sort 切换到 Tim sort。它可能会导致“损坏的比较器”的顺序略有变化(引用Arrays class源代码中的注释):

/**
 * 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

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

【讨论】:

    【解决方案2】:

    有一点需要注意,这可能会引起混乱。 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]
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 2010-10-31
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 2013-02-11
      相关资源
      最近更新 更多