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?
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 .
Collections. sort() Operates on List Whereas Arrays. sort() Operates on an Array. Arrays.
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.
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.
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.
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.
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