Kar*_*n L 36 java arrays generics instantiation map
我可以使用泛型声明一个地图数组来指定地图类型:
private Map<String, Integer>[] myMaps;
Run Code Online (Sandbox Code Playgroud)
但是,我无法弄清楚如何正确实例化它:
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
Run Code Online (Sandbox Code Playgroud)
如何在不收到编译器错误或警告的情况下实例化此数组映射?
更新:
谢谢大家的回复.我最终得到了List建议.
Bil*_*ard 40
不严格地回答你的问题,但是你考虑过用List?
List<Map<String,Integer>> maps = new ArrayList<Map<String,Integer>>();
...
maps.add(new HashMap<String,Integer>());
Run Code Online (Sandbox Code Playgroud)
似乎工作得很好.
参见Java理论和实践:泛型得到了详细解释为什么不鼓励将数组与泛型混合的详细解释.
正如Drew在评论中所提到的,使用Collection接口代替它可能更好List.如果您需要更改为a Set或其他子接口之一,这可能会派上用场Collection.示例代码:
Collection<Map<String,Integer>> maps = new HashSet<Map<String,Integer>>();
...
maps.add(new HashMap<String,Integer>());
Run Code Online (Sandbox Code Playgroud)
以此为起点,你只需要改变HashSet到ArrayList,PriorityQueue或实现任何其他类Collection.
Lau*_*ves 20
您无法安全地创建通用数组.有效的Java第二版详见了泛型一章.从第119页的最后一段开始:
为什么创建通用数组是非法的?因为它不是类型安全的.如果它是合法的,那么编译器在正确的程序中生成的强制转换可能会在运行时失败
ClassCastException.这将违反通用类型系统提供的基本保证.为了使其更具体,请考虑以下代码片段:
Run Code Online (Sandbox Code Playgroud)// Why generic array creation is illegal - won't compile! List<String>[] stringLists = new List<String>[1]; // (1) List<Integer> intList = Arrays.asList(42); // (2) Object[] objects = stringLists; // (3) objects[0] = intList; // (4) String s = stringLists[0].get(0); // (5)让我们假设创建通用数组的第1行是合法的.第2行创建并初始化
List<Integer>包含单个元素的内容.第3行将List<String>数组存储 到Object数组变量中,这是合法的,因为数组是协变的.第4行将数据存储List<Integer>到Object数组的唯一元素中,因为泛型是通过擦除实现的:List<Integer>实例的运行时类型很简单List,实例的运行时类型List<String>[]是List[],因此这个赋值不生成ArrayStoreException.现在我们遇到了麻烦.我们已经将一个List<Integer>实例存储到一个声明只包含实例的数组中List<String>.在第5行中,我们从此数组中的唯一列表中检索唯一元素.编译器自动将检索到的元素强制转换为String,但它是一个Integer,所以我们ClassCastException在运行时得到了一个 .为了防止这种情况发生,第1行(创建通用数组)会生成编译时错误.
因为数组和泛型不能很好地结合(以及其他原因),所以通常使用Collection对象(特别是List对象)而不是数组更好.
通常,在Java中混合泛型和数组并不是一个好主意,更好地使用ArrayList.
如果必须使用数组,处理此问题的最佳方法是将数组创建(示例2或3)放在单独的方法中,并使用@SuppressWarnings("unchecked")对其进行注释.