Why list.sort does not use an additional API

Java 8 introduces a new default method in the List interface to sort it. His signature:

 void sort(Comparator<? super E> c) 

The documentation says:

If the specified comparator is zero, then all the elements in this list should implement the Comparable interface, and natural should use order.

So, if you want to sort the list in its natural order (and so that your items are comparable), you must do list.sort(null); , which is rather strange from my opinion.

If they used Optional , the document would indicate that you can optionally provide a comparator, and if it is not provided, it is assumed that the elements are already comparable.

A list.sort(null); the call will be converted to list.sort(Optional.empty()); .

As a method that he exposed to the outside world, I would find it more accurate.

Why didn't they use the new optional API instead?

+5
source share
2 answers

Optional is intended to be used as a return type. It has always been the mantra of the JDK-8 developers. Therefore, they will not break their rule by using it as an argument.

However, I would make the argument mandatory and thus force the developer to use

 list.sort(Comparator.<Foo>naturalOrder()); 

Even if I can pass a null value, I find it more readable and no more verbose. So what I use in my code.

+12
source

The default method delegates to Arrays#sort , which exists since at least Java 1.7 .

Here is the appropriate snippet for the default method:

 @SuppressWarnings({"unchecked", "rawtypes"}) default void sort(Comparator<? super E> c) { Object[] a = this.toArray(); Arrays.sort(a, (Comparator) c); ListIterator<E> i = this.listIterator(); for (Object e : a) { i.next(); i.set((E) e); } } 

Note that it converts the list into an array and allows Arrays#sort process it from there. The default behavior for this will then revert to what is supported for this method.

There are two reasons why I can see that this is preferable to adding Optional :

  • If you don’t have Comparator to use or just require the default behavior, you can provide it with null . In this context, null and Optional.isPresent() fulfill the same goal and will not receive any usability points.

    It is annoying that you need to provide null functions for default behavior; the best design, perhaps, was to either overload the method or allow the default instance of naturalOrder to be used instead.

  • The Optional sample is more designed to protect against inadvertent processing of a null reference, rather than to check for null . The overhead of adding Optional , where a simple null check is sufficient, will greatly outweigh its advantages, especially since there is no semantic difference.

+1
source

Source: https://habr.com/ru/post/1235057/


All Articles