cocos2dbeginner cocos2dbeginner - 10 days ago 7
Java Question

How does Collections.sort(...) work?

To be clear, I am trying to find out how Collections.sort(list, new MyComp()) method calls the compare method in which sequence.

I have a LinkedList with Employees and their personal number (k):
The numbers are:
{1,2,3,4,5,6}
the compare(Object o1, Object o2) method in MyComparator gives back some number (which is not relevant for this concern).
How does sort() call the method compare?
Does it call it with the parameters 1,2 then, 2,3 then 3,4 then 4,5 then 5,6? I debug it but there's some strange sequence where it jumps back and also compares 1,3.

What exactly does it compare? Any pattern?

Answer

The specific comparisons made depend on what algorithm, internally, the Collections.sort method is using to sort the elements. According to the Javadoc for Collections.sort:

The documentation for the polymorphic algorithms contained in this class generally includes a brief description of the implementation. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort does not have to be a mergesort, but it does have to be stable.)

In other words, Java implementations are free to use whatever sorting algorithm they'd like, provided that it keeps equal elements in the same relative order. This means that without more knowledge of your specific Java implementation, there's no way to know what comparisons are going to be made. (If I remember correctly, the Oracle version of Java actually switched its implementation of Collections.sort from Java 7 to Java 8, though I may be mistaken.)

That said, that's not a bad thing. The idea behind writing a comparator is to tell the sorting method "do whatever you need to do to sort things, and if you ever need to make a comparison, here's the way to do it." It's a nice abstraction - you say how to rank things, and the Magic Black Box of Sorting then goes and uses it to get things into order.

Comments