I'm reviewing the source code for JDK classes.
The following method signature has me confused:
public static <T extends Comparable<? super T>> void sort(List<T> list);
Since the method doesn't return anything what are all the formal type parameters for?
How would the behavior of the method change if it's signature were only this:
public static void sort(List<T> list);
If it was
public static void sort(List<T> list);
Java would have no idea the T type was supposed to be inferred from the argument. It'd look for a concrete class or interface named T, fail to find one, and spit compiler errors at you.
The syntax:
public static void sort(List<T> list);
is not legal, because T has not been declared. The closest code with correct syntax is:
public static void sort(List<?> list);
This means the method will accept a List of any kind, but to sort the list, there must be some way to compare its elements - hence the original signature:
public static <T extends Comparable<? super T>> void sort(List<T> list);
which means each element can be compared with every other element via the compareTo() method.
The syntax:
void sort(List<? extends Comparable> list)
Is not nearly as useful - it just requires that the list contain objects that are Comparable, but not necessarily to each other. For example, such as list could contain a String and an Integer, both of which are Comparable, but not to each other - you could not meaningfully sort such a list. This is because the unknown type can be different for every element. However, by typing the method, the type can still be any type, but it's the same type for all elements of the list.
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