Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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

like image 250
user2079650 Avatar asked Feb 17 '13 02:02

user2079650


1 Answers

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.

like image 165
Jonathan Callen Avatar answered Oct 10 '22 17:10

Jonathan Callen