Java generics and addall methods

Addall (..) in Java collection What is the correct parameter type for the method? 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);

I know I need to initialize these two 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[]>> is not applicable for the arguments 
     (Collection<HashMap<String,Object[]>>)

What on earth did I do wrong?

Solution

You can only insert instances of T into list < T >

Type list > represents a list of unknown types T, and its extended map < x, Y > For example, it can represent list < LinkedHashMap < x, Y > > Obviously, you may not be able to insert an ordinary HashMap < x, Y > into such a list

You may want to:

List<Map<String,Object[]>> currentList;

Or if you want to be very flexible, you can do this:

List<? super Map<String,Object[]>> currentList;

This will allow you to do crazy things, such as:

currentList = new ArrayList<Map<? super String,? extends Object[]>>();

You may also want to read Angelika Langer's genetics FAQ, especially the section about wildcards

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>