Reputation: 51
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.
Upvotes: 5
Views: 2571
Reputation: 33351
One thing to note, that might be causing confusion. Collections.sort is a stable sort. This means for equal elements, it maintains their original ordering, so:
if a == b, then
Collections.sort([d, e, b, a, c, f, g, h]) = [b, a, c, d, e, f, g, h]
and
Collections.sort([d, e, a, b, c, f, g, h]) = [a, b, c, d, e, f, g, h]
Seems likely to me that either that is what your seeing, or the Comparator in question (or the objects being sorteds' natural ordering) isn't working the way you expect it to.
Upvotes: 0
Reputation: 340873
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.
Upvotes: 9