Java泛型和addAll方法 [英] java generics and the addAll method
问题描述
Java集合中addAll(..)方法的正确参数类型是什么?如果我这样做:
What is the correct type of argument to the addAll(..) method in Java collections? If I do something like this:
List<? extends Map<String, Object[]>> currentList = new ArrayList<Map<String, Object[]>>();
Collection<HashMap<String, Object[]>> addAll = new ArrayList<HashMap<String, Object[]>>();
// add some hashmaps to the list..
currentList.addAll(addAll);
我知道我需要初始化两个变量。但是,我得到了一个编译错误(来自eclipse):
I understand I need to initialize both variables. However, I get a compilation error (from eclipse):
Multiple markers at this line
- The method addAll(Collection<? extends capture#1-of ? extends Map<String,Object[]>>) in the type List<capture#1-of ? extends Map<String,Object[]>> is not applicable for the arguments (List<capture#2-of ? extends
Map<String,Object[]>>)
- The method addAll(Collection<? extends capture#1-of ? extends Map<String,Object[]>>) in the type List<capture#1-of ? extends Map<String,Object[]>> is not applicable for the arguments
(Collection<HashMap<String,Object[]>>)
我在做什么错?
推荐答案
您只能将 T
的实例插入列表< T>
。
You can only insert instances of T
into a List<T>
.
列表类型?扩展Map< X,Y>>
表示 unknown 类型 T
的列表,其中扩展Map< X,Y>
。例如,它可以代表 List< LinkedHashMap< X,Y>>
。显然,您可能不会在这样的列表中插入普通的 HashMap< X,Y>
。
The type List<? extends Map<X,Y>>
stands for a list of an unknown type T
which extends Map<X,Y>
. For instance, it could stand for a List<LinkedHashMap<X,Y>>
. Obviously, you may not insert an ordinary HashMap<X,Y>
into such a list.
:
List<Map<String, Object[]>> currentList;
或者,如果您想变得真正灵活,可以这样做:
Or if you want to be really flexible you could do:
List<? super Map<String, Object[]>> currentList;
这会让您做疯狂的事情,例如:
Which would allow you to do crazy things like:
currentList = new ArrayList<Map<? super String, ? extends Object[]>>();
您可能还希望阅读Angelika Langer的泛型常见问题解答,尤其是有关通配符的部分。
You might also wish to read Angelika Langer's Generics FAQ, particularly the section about wildcards.
这篇关于Java泛型和addAll方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!