Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java generics and the addAll method

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

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[]>>)

what am I doing wrong?

like image 675
neesh Avatar asked Apr 23 '10 19:04

neesh


People also ask

What does addAll method do?

The addAll() method of java. util. Collections class is used to add all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array.

What is generic methods in Java?

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

Do generics prevent type cast errors?

Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.

How do you use addAll?

addall() method in Java. Below are the addAll() methods of ArrayList in Java: boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.


2 Answers

Replace extends by super.

The addAll() itself takes an ? extends T argument and that won't work when T is ? extends Map<K, V>. With the change it will become effectively ? extends ? super Map<K, V>.

But still, better is just to remove that ? extends (or ? super). It's superfluous in this particular case. Just use List<Map<String, Object[]>>. The addAll() will then effectively take ? extends Map<String, Object[]>>.

like image 154
BalusC Avatar answered Nov 03 '22 08:11

BalusC


just remember:

for <? extends ...>, you cannot put things (except null) into it

for <? super ...>, you cannot get things (except Object) out of it

like image 40
newacct Avatar answered Nov 03 '22 06:11

newacct