CCC
CCC

Reputation: 2761

can't add generic list to generic map

I have a generic map

Map<String, List<A<?>>> map = new HashMap<>();

then I have a list like:

List<A<Integer>> list1 = getData();
List<A<String>> list2 = getData2();

I'm trying to add them to the map, but I'm getting an error saying the argument is wrong.

map.put("a", list1);
map.put("b", list2);
//doesn't work

Making the map like

Map<String, List<A>> map = HashMap<>();

doesn't work either. How can I change "map" to be able to add those 2 lists?

Upvotes: 1

Views: 1204

Answers (2)

pranavmalhotra
pranavmalhotra

Reputation: 152

If you just want to place any two lists inside the map then use: Map<String, List> map = new HashMap<>();.

Alternatively, if you want to restrict the type of the List that you would like to add:

Map<String, List<? extends Object>> map = new HashMap<>();.

Why I have chosen to extend Object is because it is the only class present in the hierarchies of both Integer and String.

Upvotes: -2

VGR
VGR

Reputation: 44308

Generics are not evaluated recursively. The wildcard (<?>) does not get evaluated here.

If you have a Map<String, List<A<?>>> then you must add List<A<?>> values to it; List<A<Integer>> does not qualify as a List<A<?>>. List<A<?>> means a List of A instances with unknown types, so you must pass a List of A instances with unknown types.

What you can do is create such a List, explicitly, and add all the elements of your typed-A List to it:

List<A<Integer>> list1 = getData();
List<A<String>> list2 = getData2();

List<A<?>> list1Unknown = new ArrayList<>();
list1.forEach(list1Unknown::add);

List<A<?>> list2Unknown = new ArrayList<>();
list2.forEach(list2Unknown::add);

map.put("a", list1Unknown);
map.put("b", list2Unknown);

Upvotes: 3

Related Questions