怎样才能实例化的Java地图的数组? [英] How does one instantiate an array of maps in Java?
问题描述
我可以使用泛型指定地图类型声明映射的数组:
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?
更新:
感谢大家的回复。我结束了名单的建议下去。
Thank you all for your replies. I ended up going with the List suggestion.
推荐答案
不是严格意义上的回答你的问题,但你有没有考虑使用列表
呢?
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.
请参阅 Java理论与实践:泛型陷阱获取详细的解释,为什么混合泛型数组是不鼓励。
See Java theory and practice: Generics gotchas for a detailed explanation of why mixing arrays with generics is discouraged.
由于在评论中提到的德鲁,它可能是更好的使用的收藏接口而不是列表
。这可能会派上用场,如果你需要更改为设置
或收藏
其他子接口之一。例如:code:
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>());
从这个出发点,你只需要修改 HashSet的
到的ArrayList
,的PriorityQueue
,或者任何其它类实现收藏
。
From this starting point, you'd only need to change HashSet
to ArrayList
, PriorityQueue
, or any other class that implements Collection
.
这篇关于怎样才能实例化的Java地图的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!