How does one instantiate an array of maps in Java?

Question:

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?

Ansewer:

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 ArrayListPriorityQueue, or any other class that implements Collection.

猜你喜欢

转载自blog.csdn.net/qq_36396104/article/details/82794808