"Cannot create generic array of .." - how to create an Array of Map<String, Object>?
I would like to use simpleJdbcInsert class and executeBatch method
public int[] executeBatch(Map<String,Object>[] batch)
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/simple/SimpleJdbcInsert.html
So I need to pass an array of Map<String,Object>
as parameter. How to create such an array?
What I tried is
Map<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 of Map<String, Object>
?
Thanks
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.
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);