Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding generic parameters with void return types

Tags:

java

generics

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);
like image 897
Kshitiz Sharma Avatar asked Aug 04 '26 00:08

Kshitiz Sharma


2 Answers

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.

like image 65
user2357112 supports Monica Avatar answered Aug 07 '26 04:08

user2357112 supports Monica


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.

like image 30
Bohemian Avatar answered Aug 07 '26 02:08

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!