我可以使用泛型声明一个映射数组来指定映射类型:
private Map<String, Integer>[] myMaps;
但是,我不知道如何正确实例化它:
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
如何实例化这个映射数组而不出现编译器错误或警告?
更新:
感谢大家的回复。我最终选择了 List 建议。
最佳答案
严格来说不是您问题的答案,但您是否考虑过使用 List
代替?
List<Map<String,Integer>> maps = new ArrayList<Map<String,Integer>>();
...
maps.add(new HashMap<String,Integer>());
似乎工作得很好。
见 Java theory and practice: Generics gotchas有关为什么不鼓励将数组与泛型混合使用的详细说明。
更新:
正如 Drew 在评论中提到的,使用 Collection 可能会更好。接口(interface)而不是 List
。如果您需要更改为 Set
或 Collection
的其他子接口(interface)之一,这可能会派上用场。示例代码:
Collection<Map<String,Integer>> maps = new HashSet<Map<String,Integer>>();
...
maps.add(new HashMap<String,Integer>());
从此开始,您只需将 HashSet
更改为 ArrayList
、PriorityQueue
或任何其他实现 的类> Collection
.
关于java - 如何在 Java 中实例化一组 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1493162/