I'm reading the book Java generics and collections
by Maurice Naftalin.
In the section on wildcard capturing, the author gave an example
public static void reverse(List<?> list) {
rev(list);
}
private static <T> void rev(List<T> list) {
List<T> tmp = new ArrayList<T>(list);
for (int i = 0; i < list.size(); i++) {
list.set(i, tmp.get(list.size()-i-1));
}
}
But I thought type List<T>
is a subtype of List<?>
(where List<?>
is a shorthand syntax for List<? extends Object>
) (is my assumption of List<T>
is a subtype of List<? extends Object>
even correct?), so inside the reverse
method, how can we pass variable list
(of type List<? extends Object>
) to rev
method, where the rev
method's parameter is of type List<T>
?
how can we pass variable list (of type
List<? extends Object>
) to rev method
You're not.
Every list has a type: you can't create a new ArrayList<?>
or a new ArrayList<? extends String>
. You can create a new ArrayList<String>
, and assign it to a variable with a wildcard type.
So, you can invoke a method taking List<T>
, even with a List<?>
as the parameter, provided the compiler can infer that there is some type which is consistent with the bounds. You don't know the type, but the compiler can.
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