在Java中如何实例化地图数组? [英] How does one instantiate an array of maps in Java?

查看:211
本文介绍了在Java中如何实例化地图数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  private Map< String,Integer> [p]我可以使用泛型来声明一个地图数组来指定地图类型: ] myMaps; 

但是,我无法弄清楚如何正确实例化:

  myMaps = new HashMap< String,Integer> [count]; //给出通用数组创建错误
myMaps = new HashMap [count]; //给出未检查或不安全的操作警告
myMaps =(Map< String,Integer> [])new HashMap [count]; //还给出警告

如何在没有编译器错误或警告的情况下实例化这个地图数组?



更新:



感谢大家的回复。我结束了列表建议。

解决方案

不是严格的答案你的问题,但你考虑使用一个列表

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

似乎工作正常。



有关详细说明,请参阅 Java理论和实践:泛型as as为什么混淆数组与仿制药是不鼓励的。



更新:



如Drew在评论中所提到的,更好地使用收集界面的列表。如果您需要更改为 Set Collection 的其他子界面之一,则可能会派上用场。示例代码:

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

从这个起点,您只需要更改 HashSet to ArrayList PriorityQueue 或任何其他实现 Collection


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.

解决方案

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.

这篇关于在Java中如何实例化地图数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆