I have the following code but i am confused with all the generics.
public static <T> List<T> backwards (List<? super T> input) {
List<T> output = new ArrayList<T>();
return output;
}
My understanding is that I have a public method named backwards
which creates an arraylist implementing the List interface and returning the arraylist. My question is what actually I am saying to the compiler with the following part......
static <T> List<T> backwards (List<? super T> input)
super T denotes an unknown type that is a supertype of T (or T itself; remember that the supertype relation is reflexive). It is the dual of the bounded wildcards we've been using, where we use ? extends T to denote an unknown type that is a subtype of T .
super is a lower bound, and extends is an upper bound.
T is an "unbound" type. In other words, List<T> is shorthand for "list of things".
super Integer> is a unbounded List that accepts any value that is a Integer or a superclass of Integer . The 2nd option is best used on the PECS Principle (PECS stands for Producer Extends, Consumer super). This is useful if you want to add items based on a type T irrespective of it's actual type.
You are saying to the compiler:
<T>
"I'm declaring an arbitrary type T
for this method, which can be anything (non-primitive) for each call of the method."
List<T>
"This method will return a List
containing elements of that type T
."
List<? super T> input
"This method will take a parameter called input
, which is a List
containing elements of type T
, or any super-type of T
. For example, if T
is Integer
, input
could be a List<Integer>
, List<Number>
, or List<Object>
."
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