I'm looking for how to pass as a parameter of a method a linkedList of a type which implements the Comparable interface.
public static void mergeSort(LinkedList<Comparable> list){}
I tried that but when I pass a primitive type such as Integer as a parameter it doesn't work. If someone have an idea?
You need to specify a bound parameter:
public static <T extends Comparable<? super T>> void mergeSort(LinkedList<T> list){}
This is taken from the method sort .
Simply let the compiler know that the input type T
extends Comparable<T>
.
public static <T extends Comparable<T>> void mergeSort(final LinkedList<T> list)
I would not use the ?
, which is a wildcard and represents an unknown type .
Explicitly specifying the generic type is always better (see this question ).
Define a type parameter, and use that type parameter as the element type:
public static <C extends Comparable<? super C>> void mergeSort(LinkedList<C> list){}
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.