Java – why list Sort does not use the optional API

Java 8 introduces a new default method on the list interface to sort it Its signature is:

void sort(Comparator<? super E> c)

The document says:

Therefore, if you want to sort the list in its natural order (and your elements are comparable), you must execute list sort(null); It's a little strange, my opinion

If they use optional, Doc will say that you can choose to provide a comparator. If not, it will think that these elements are already comparable

list. sort(null); Call will be converted to list sort(Optional.empty());.

Because it is a way to expose to the outside world, I will find it more accurate

Why don't they use the new optional API?

Solution

Optional as return type This has always been the mantra of JDK - 8 developers Therefore, they will not break their rules by using it as an argument

That is, I will force the argument to force developers to use it

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

Even if I can pass null, I find the above content more readable and verbose This is what I use in the code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>