Java泛型放在Map< String,? extends List< String>> [英] Java Generics putting on Map<String, ? extends List<String>>
问题描述
有没有办法以类型安全的方式使以下实现?
Is there a way to make the following implementation in a type safe manner?
public void myMethod( Map<String, ? extends List<String>> map )
{
map.put("foo", Collections.singletonList("bar");
}
上面的实现不起作用,它需要一个 Map< String,?super List< String> / code>正确地编译方法
map.put()
但是myMethod不会接受List的任何子类型因此,我必须使用 Map< String,?extends List< String>>
而不是如何以类型安全的方式解决这个问题?
The above implementation doesn't work. It requires a Map<String, ? super List<String>>
to compile the method map.put()
correctly. But myMethod won't accept any subtype of List this way. So, I have to use Map<String, ? extends List<String>>
instead. How can I solve this problem in a type safe manner?
推荐答案
public void myMethod( Map<String, List<String>> map ) {
map.put("foo", Collections.singletonList("bar") );
}
列表(
Collection.singletonList()的返回类型
转换为映射$
? extends List
,因为实际类型可以是 List
的任何实现。例如,将通用列表
放入 Map< String,LinkedList> $ c中是不安全的$ c>,因为
List
可能不是 LinkedList
。然而,我们可以很容易地将 LinkedList
放入
You can't put a List
(the return type of Collections.singletonList()
into a Map
of ? extends List
since the actual type could be any implementation of List
. For example, it is not safe to put a generic List
into a Map<String,LinkedList>
since the List
might not be a LinkedList
. However, we can easily put a LinkedList
into a Map
of <String,List>
.
我想你是在想你的泛型。您不必使用? extends
用于非泛型类。例如, List< Object>
将保存任何 Object
,? extends
不需要添加对象。 列表< List< Foo>>
将只需要 List< Foo>
对象,而不是 List< FooSubclass>
objects [通用类不根据参数继承]。这是? extends
开始运行。将列表< Foo>
和列表< FooSubclass>
添加到列表
,类型必须 List< List< ;?扩展Foo>>
。
I think you were over thinking your generics. You do not have to use ? extends
for a non-generic class. For example, List<Object>
will hold any Object
, the ? extends
is not needed to add an object. A List<List<Foo>>
will only take List<Foo>
objects and not List<FooSubclass>
objects [Generic classes don't inherit based on their parameters]. This is where ? extends
comes into play. To add both List<Foo>
and List<FooSubclass>
to a List
, the type must be List<List<? extends Foo>>
.
这篇关于Java泛型放在Map< String,? extends List< String>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!