Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New sort method added in List after using Collections.sort [duplicate]

Why is a new sort method added in java.util.List in java 8 when we have a provision to sort lists using Collections.sort

like image 736
shuchita khurana Avatar asked Apr 05 '18 05:04

shuchita khurana


People also ask

What sorting method does Collections sort use?

So, in the end, Collections#sort uses Arrays#sort (of object elements) behind the scenes. This implementation uses merge sort or tim sort.

Does Collections sort work on a set?

Yes, the Collections. sort methods are only for lists. You can't sort HashSet , but a TreeSet is automatically sorted as you add items, and LinkedHashSet is sorted by insertion order. Show activity on this post.

Which collection is best for sorting in Java?

If you want to maintain a sorted list which you will frequently modify (i.e. a structure which, in addition to being sorted, allows duplicates and whose elements can be efficiently referenced by index), then use an ArrayList but when you need to insert an element, always use Collections.


2 Answers

  1. because it makes the API more intuitive and OO
  2. because it allows implementations of List to use a faster sorting algorithm, best suited to their internal structure. For example, ArrayList can sort its internal array without first doing a copy as the default implementation does.
like image 164
JB Nizet Avatar answered Oct 17 '22 14:10

JB Nizet


JB Nizet's answer already gives you reasons why it was a good idea to add this method. The second aspect of this is:

If it is so obviously a good idea to add this method, why hasn't it been added in some earlier version?

Both the List interface and the static utility Collections were added in the same version 1.2, so it would have been possible to include it from the start.

After that opportunity had been missed, there was no way to add it any more. Adding a method to an interface was a change that would have broken backward-compatibility prior to the introduction of default-methods in Java 1.8.

like image 27
Hulk Avatar answered Oct 17 '22 16:10

Hulk