60

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?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
user5539357
  • 1,024
  • 1
  • 9
  • 19
  • 3
    list.sort() could not be introduced until default methods were made available on interfaces in java 8 – Thorbjørn Ravn Andersen Jan 20 '16 at 21:30
  • I fail to see why list.sort could not be introduced without default methods. – emory Jan 21 '16 at 02:33
  • 5
    @emory Before default method support was added, introducing a new method to an interface would break every existing implementation of the interface. – Pieter Müller Apr 13 '17 at 16:25
  • 1
    I don't want to be picky, however, you can't use `list.sort()` as it requires an argument. So if you prefer to take List's sort, you need to write `list.sort(null)`. Then everybody reading your code wonders, what `null`means -> natural order. For reasons of simplicity and readability I would stick to `Collections.sort(list)` if you use natural ordering. IMHO – math Apr 13 '22 at 17:50

3 Answers3

55

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.

Community
  • 1
  • 1
Tunaki
  • 132,869
  • 46
  • 340
  • 423
11

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.

MobA11y
  • 18,425
  • 3
  • 49
  • 76
8

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.

Javier S López
  • 101
  • 1
  • 3