Compilation error with generics wildcard methods

valoo86 :

I thought i was comfortable with generics until i faced this problem :

I have the following class:

public class Item<T> {
    T item;

    public T getItem() {
        return item;
    }
}

and the following methods:

public static void myFunction1(Map<?, String> map) {
    //some code
}

public static void myFunction2(Map<Item<?>, String> map) {
    //some code
}

And when i call myFunction1 and myFunction2:

myFunction1(new HashMap<Item<String>, String>()); //compilation OK
myFunction2(new HashMap<Item<String>, String>()); //compilation error

I don't understand why when i call myFunction2 i get a compilition error, i read many articles and documentations about generics and i don't understand why.

Can somebody could explain why ? Thanks a lot !

Andrew Tobilko :

You probably meant

public static void myFunction2(Map<? extends Item<?>, String> map)

An Item<String> is not an Item<?>, but an Item<String> is a ? extends Item<?>, or, more broadly, a ?.

Look at this tutorial, there is a good hierarchy diagram at the end.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148715&siteId=1