Difference between Collections.sort(list) and list.sort(Comparator)
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?
Solution 1:
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.
Solution 2:
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.
Solution 3:
The simple answer is that Collections.sort
delegates to List.sort
. Since one call delegate to the other there are equivalent. However, it is preferable to use List.sort
to simply avoid the extra method call.