How does one instantiate an array of maps in Java?

Viewed 83025

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.

7 Answers

I know its a bit late to reply but I found this workaround helpful for my case...Hope it helps!

Use an array of HashMap to store HashMaps..

public static void main(String[] args) {
    HashMap[] arr = new HashMap[1];//creating an array of size one..just for sake of example
    HashMap<String, String> arrMap = new HashMap<String, String>();

    //use loops to store desired key-value pairs into the HashMap which will be stored inside the array
    arrMap.put("ABC", "Name");

    //use loop to store your desired hashMap into the array at a particular index
    arr[0] = arrMap;

    //desired manipulation of the stored array.
    System.out.println(arr[0]);
}
Related