Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections.sort() issue in java7

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.

like image 264
user1011337 Avatar asked Dec 07 '12 18:12

user1011337


People also ask

What does collection sort () do?

By default, Collection. sort performs the sorting in ascending order. If we want to sort the elements in reverse order we could use following methods: reverseOrder() : Returns a Comparator that imposes the reverse of natural ordering of elements of the collection.

Can we use Collections sort () in array in Java?

It works on array input. Collections. sort() can sort objects on both contiguous and discrete memory locations: i.e. it can work on both ArrayList and LinkedList . Collections.

How do you sort data in Collections?

Collections. sort() works for objects Collections like ArrayList, LinkedList, etc. We can use Collections. sort() to sort an array after creating an ArrayList of given array items.

Which sorting is used in Collections sort?

So, in the end, Collections#sort uses Arrays#sort (of object elements) behind the scenes. This implementation uses merge sort or tim sort.


1 Answers

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.

like image 58
Tomasz Nurkiewicz Avatar answered Nov 10 '22 02:11

Tomasz Nurkiewicz