Wildcard java method argument and parameter type

I read a book by Java generics and collectionsMaurice Naphthalene.

In the section on capturing wildcards, 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 that the type List<T>is a subtype List<?>(where List<?>is the shorthand syntax for List<? extends Object>) (is my assumption about the List<T>subtype List<? extends Object>even correct?), So inside the method reverse, how can we pass a variable list(type List<? extends Object>) to a method revwhere the method parameter revhas a type List<T>?

+4
source share
3 answers

how can we pass a list of variables (type List<? extends Object>) to the rev method

No.

: new ArrayList<?> new ArrayList<? extends String>. new ArrayList<String> .

, , List<T>, List<?> , , , . , .

+3

, List<T> List<?>

: , Java . , X Y, List<X> List<Y>.

, , , reverse List, .

+2

:

private static <T> void rev(List<T> list) {...}

T is a parameter parameterized by a method that, without explicit binding, refers to any type.

You can pass in a method a variable declared as List<? extends Object>, List<?>or even List<String>since it takes any type in List.

+2
source

Source: https://habr.com/ru/post/1696019/


All Articles