无法将通用列表添加到通用地图 [英] can't add generic list to generic map

查看:56
本文介绍了无法将通用列表添加到通用地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张通用地图

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

使地图像

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

也不起作用.如何更改地图"以能够添加这两个列表?

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

推荐答案

对泛型不进行递归评估.通配符(<?> )在此处未求值.

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

如果您有 Map< String,List< A<?>>> ,那么您必须添加 List< A<?>> 值; List< A< Integer>> 不符合 List< A<?<?> 的资格. List< A<?>> 表示具有未知类型的A实例的列表,因此您必须传递具有未知类型的A实例的列表.

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.

您可以做的是,显式地创建一个这样的列表,并向其中添加键入的A列表的所有元素:

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);

这篇关于无法将通用列表添加到通用地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆