Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wildcard capturing java method argument and parameter type

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>?

like image 643
Thor Avatar asked Mar 06 '23 11:03

Thor


1 Answers

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.

like image 59
Andy Turner Avatar answered Mar 22 '23 16:03

Andy Turner