简体   繁体   中英

Type Bounds In Java Array (sort or minimum) Function

In Java, the Arrays.sort generic function is declared as follows:

public static <T> void sort(T[] a, Comparator<? super T> c)

Can an example be provided when the above definition would succeed, but the following would not:

public static <T> void sort(T[] a, Comparator<T> c)
Comparator<CharSequence> onLength = Comparator.comparingInt(CharSequence::length);
String[] test = {"hello", "you"};
Arrays.sort(test, onLength);
System.out.println(Arrays.toString(test));

The above would fail if the signature was simply sort(T[] a, Comparator<T> c) - in that case, only a Comparator<String> would suffice.

You could have trivially written:

Comparator<String> onLength = Comparator.comparingInt(String::length);

but what if you already have a comparator, or there is a class that provides it for you? You can't just 'cast' a Comparator<CharSequence> to Comparator<String> .

The idea is: A thing that can compare any 2 fruits can of course compare any 2 apples. The user of the thing needs to tell the compiler that it works like that, and you do this by saying <? super T> <? super T> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM