Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Collections.sort(list) and list.sort(Comparator)

Tags:

java

list

sorting

Is there any reason why I should prefer Collections.sort(list) method over simply calling the list.sort()? Internally Collections.sort merely calls the sort method of the List class anyway.

It's just surprising that almost everyone is telling me to use Collections.sort. Why?

like image 870
user5539357 Avatar asked Jan 20 '16 21:01

user5539357


People also ask

Does collections sort use Comparator?

Collection. sort(1, Comparator) uses a custom comparator to compare the contents of l , this is what you did. The very idea of sorting (including the sort() method) implies the objects MUST be comparable - in this case, with either Comparable or Comparator .

What is the difference between arrays sort and collections sort?

Collections. sort() Operates on List Whereas Arrays. sort() Operates on an Array. Arrays.

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.

Which method is used to sort using Comparator?

Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else. Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator.


2 Answers

The method List.sort(comparator) that you are refering to was introduced in Java 8, whereas the utility method Collections.sort has been there since Java 1.2.

As such, you will find a lot of reference on the Internet mentioning that utility method but that's just because it has been in the JDK for a lot longer.

Note that the change in implementation for Collections.sort was made in 8u20.

like image 90
Tunaki Avatar answered Oct 10 '22 23:10

Tunaki


This is simply a change to the APIs. With a language with such wide spread adoption as Java, what typically happens is for a period of time, the older method is preferable, to maintain legacy support.

After this period of time, the older API becomes deprecated (or perhaps not, both can remain in place indefinitely). Within this time period improvements may be made to the new API causing its functionality to diverge slightly from the original implementation, encouraging developers to adopt it. The requirements/results of the new API may diverge slightly, and the implementation may change dramatically.

Then, eventually, the new API takes over, and the older API is no longer required and removed. In a language with as wide of adoption as Java this can take years, or decades. Developers can have a plan to remove an API, but be forced to leave it in by the community.

like image 22
ChrisCM Avatar answered Oct 10 '22 22:10

ChrisCM