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?
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.
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.
Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.
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.
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[]>>
.
just remember:
for <? extends ...>
, you cannot put things (except null) into it
for <? super ...>
, you cannot get things (except Object) out of it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With