Domas Mar Domas Mar - 1 year ago 74
Java Question

Using parent classes in Java generics parameters

I don't understand how generics in Java fully works. I have similar situation which I simplified in code below:

public static void main(String[] args) {
Map<String, Collection<B>> map1 = test();
Map<String, List<B>> map2 = test();
Map<String, ArrayList<B>> map3 = test();
}

private static Map<String, ArrayList<B>> test() {
return null;
}


when creating map1 or map2 I get an error which says incompatible type - it was expecting ArrayList, but got Collection/List instead.

How do I solve such problem?

Answer Source

Here's the code which will compile successfully:

public static <B> void main(String[] args) {
    Map<String, ? extends Collection<B>> map1 = test();
    Map<String, ? extends List<B>> map2 = test();
    Map<String, ArrayList<B>> map3 = test();
}

private static <B> Map<String, ArrayList<B>> test() {
    return null;
}

You need to add ? extends Collection<B> and ? extends List<B> because writing ? extends Collection means that the Object which forms the value of the Map is a sub type of Collection class and thus the test() will be called as it also returns a Map whose value is ArrayList type, which is actually a sub type of Collection

Also note that you need to add <B> in the signatures of main and test()

Hope it helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download