0

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?

Domas Mar
  • 1,148
  • 1
  • 11
  • 23
  • 2
    You might want to see previous questions on the matter: [Why we can't do List mylist = ArrayList();](https://stackoverflow.com/questions/5763750/why-we-cant-do-listparent-mylist-arraylistchild). [How do you cast a List of supertypes to a List of subtypes?](https://stackoverflow.com/questions/933447/how-do-you-cast-a-list-of-supertypes-to-a-list-of-subtypes) – default locale Feb 07 '17 at 10:58

1 Answers1

2

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!