"Cannot create generic array of .." - how to create an Array of Map<String, Object>?
Solution 1
Because of how generics in Java work, you cannot directly create an array of a generic type (such as Map<String, Object>[]
). Instead, you create an array of the raw type (Map[]
) and cast it to Map<String, Object>[]
. This will cause an unavoidable (but suppressible) compiler warning.
This should work for what you need:
Map<String, Object>[] myArray = (Map<String, Object>[]) new Map[10];
You may want to annotate the method this occurs in with @SuppressWarnings("unchecked")
, to prevent the warning from being shown.
Solution 2
You can create generic array of map.
Create a list of maps.
List<Map<String, ?>> myData = new ArrayList<Map<String, ?>>();
Initialize array.
Map<String,?>[] myDataArray = new HashMap[myData.size()];
Populate data in array from list.
myDataArray = myData.toArray(myDataArray);
Related videos on Youtube
user2079650
Updated on July 09, 2022Comments
-
user2079650 almost 2 years
I would like to use simpleJdbcInsert class and executeBatch method
public int[] executeBatch(Map<String,Object>[] batch)
So I need to pass an array of
Map<String,Object>
as parameter. How to create such an array? What I tried isMap<String, Object>[] myArray = new HashMap<String, Object>[10]
It is error: Cannot create generic array of
Map<String, Object>
A
List<Map<String, Object>>
would be easier, but I guess I need an array. So how to create an array ofMap<String, Object>
? Thanks-
Admin about 11 yearsI would likely start with a List and turn it into an array as needed, since I dislike dealing with Java arrays .. but this is still a valid question nevertheless.
-
nneonneo about 11 years@pst: Post that as an answer. I hate casting generic arrays (my last attempt at an answer was incorrect because I forgot how broken generics were).
-
-
Diffy almost 10 yearswhen i use LinkedHashMap<String,String>map_array[] = new LinkedHashMap<String,String>[2]; , it also gives this error? Now i dont understand what is 'generic' here?
-
Jonathan Callen almost 10 years@Diffy The "generic" part is the type parameters
<String,String>
. To remove the error (and replace it with a warning), useLinkedHashMap<String, String>[] map_array = (LinkedHashMap<String, String>) new LinkedHashMap[2];
-
Diffy almost 10 yearsYes, i got out of the error by using simply new LinkedHashMap[2], but it would have been generic if i would have used an Object datatype or "T" (generic tmplate ). How come <String,String> is generic? I am specifying the proper datatype here
-
Jonathan Callen almost 10 years"Generic" in this case means "Type that has type parameters, or is defined by a type parameter". So
LinkedHashMap<String, String>
becomesLinkedHashMap
,T
becomesObject
(normally), etc.