Collections.sort() issue in java7

collections, java-7, sorting

Solution

Java 7 switched from Merge sort to Tim sort. It might result in slight changes in order with "broken comparators" (quoting comment in source code of `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.
 */

Try running your JVM with:

java -Djava.util.Arrays.useLegacyMergeSort=true

It's not clear what "broken comparator" means, but apparently it can result in different order of elements in sorted arrays.

Problem

Is there a sort issue with java7? I am using Collections.sort(list, comparator) When I switched over to java7, I noticed that the sorting resulted in a different list compared to the result when I was using java6. Example: List = [d, e, b, a, c, f, g, h] In java6 Collections.sort(List, comparator) resulted in [a, b, c, d, e, f, g, h] In java7 Collections.sort(List, comparator) resulted in [b, a, c, d, e, f, g, h] The first two values in the list have been swapped.

Original source