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.
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.
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.
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.
So, in the end, Collections#sort uses Arrays#sort (of object elements) behind the scenes. This implementation uses merge sort or tim sort.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With