I am very confused about the working principle of the compareTo()
method in Java. On passing a list through Collections.sort()
method, which objects are actually get compared to return the negative or positive or zero value?

- 7,310
- 17
- 40
- 61

- 57
- 2
- 11
-
Please refer [this SO question](http://stackoverflow.com/questions/18754490/using-compareto-and-collections-sort) – Prashant Mar 11 '16 at 16:31
-
Did you [read the docs](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-)? – resueman Mar 11 '16 at 16:31
-
All of them. You need to look at all values to sort a list (just not necessarily compare everything to everything else). – Andy Turner Mar 11 '16 at 16:34
-
You sort a list so you compare the elements of that list. – Thomas Mar 11 '16 at 16:35
-
Possible duplicate of [compareTo method java](http://stackoverflow.com/questions/10017381/compareto-method-java) – Adam B Mar 11 '16 at 16:36
3 Answers
It is used for sorting. So all elements get compared and It is ultimately used for sorting.

- 113
- 2
- 13
-
https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html Here is an example. – Karen Mar 11 '16 at 16:37
All of them, and most of them several times. Your question is really "How does sorting work", which is too broad for StackOverflow.
However, a simplified answer is that the algorithm compares pairs of elements, each time invoking compareTo()
, to decide which one is "smaller" (for some definition of "smaller"). Good sorting algorithms try to minimize the number of comparisons, but each element will have to be compared to some number of others (where that number is normally > 1).
The reason compareTo()
exists is that it allows YOU to decide what "smaller" and "greater" mean for your objects, allowing you to sort them however you want.

- 85,615
- 20
- 155
- 190
Say your list is a List<Integer>
with the values [5, 7, 3]
. Integer
has a compareTo()
.
The exact method of sorting depends on the algorithm, but lets try a simple bubblesort.
5.compareTo(7)
< 0: No action necessary7.compareTo(3)
> 0: Swap elements
List is now [5, 3, 7]
.
3.compareTo(5)
> 0: Swap elements
List is now [3, 5, 7]
, and sort has been completed.
In this particular example, all elements ended up being compared to all other elements. This is rarely the case, since smart sorting algorithms can minimize the number of comparisons necessary.

- 154,647
- 11
- 152
- 247