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.
So that's Wrong
Why not make a List of Maps instead of trying to make an array?
You can't safely create a generic array. Effective Java 2nd Edition goes into the details in the chapter on Generics. Start at the last paragraph of page 119:
Because arrays and generics don't combine well (as well as other reasons), it's generally better to use
Collection
objects (in particularList
objects) rather than arrays.Short answer appears to be that you really just can't.
See the following for a blog about it. http://www.bloggingaboutjava.org/2006/01/java-generics-quirks/
One of the comments to the blog states that:
As suggested by Bill the Lizard, you probably are better off using a
You can create generic array of map
Create list of map.
Initialize array.
Populate data in array from list.
I had a similar question, best response I got referred to this
Not strictly an answer to your question, but have you considered using a
List
instead?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 aSet
, or one of the other subinterfaces ofCollection
. Example code:From this starting point, you'd only need to change
HashSet
toArrayList
,PriorityQueue
, or any other class that implementsCollection
.