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
So, in the end, Collections#sort uses Arrays#sort (of object elements) behind the scenes. This implementation uses merge sort or tim sort.
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.
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.
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.
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