How does one instantiate an array of maps in Java?

Karl von L picture Karl von L · Sep 29, 2009 · Viewed 68.1k times · Source

I can declare an array of maps using generics to specify the map type:

private Map<String, Integer>[] myMaps;

However, I can't figure out how to instantiate it properly:

myMaps = new HashMap<String, Integer>[count]; // gives "generic array creation" error
myMaps = new HashMap[count]; // gives an "unchecked or unsafe operation" warning
myMaps = (Map<String, Integer>[])new HashMap[count]; // also gives warning

How can I instantiate this array of maps without getting a compiler error or warning?

Update:

Thank you all for your replies. I ended up going with the List suggestion.

Answer

Bill the Lizard picture Bill the Lizard · Sep 29, 2009

Not strictly an answer to your question, but have you considered using a List instead?

List<Map<String,Integer>> maps = new ArrayList<Map<String,Integer>>();
...
maps.add(new HashMap<String,Integer>());

seems to work just fine.

See Java theory and practice: Generics gotchas for a detailed explanation of why mixing arrays with generics is discouraged.

Update:

As mentioned by Drew in the comments, it might be even better to use the Collection interface instead of List. This might come in handy if you ever need to change to a Set, or one of the other subinterfaces of Collection. Example code:

Collection<Map<String,Integer>> maps = new HashSet<Map<String,Integer>>();
...
maps.add(new HashMap<String,Integer>());

From this starting point, you'd only need to change HashSet to ArrayList, PriorityQueue, or any other class that implements Collection.