Java 1.6 : Creating an array of List<T>

标签 java generics

为什么我不能创建 List 数组?

List<String>[] nav = new List<String>[] { new ArrayList<String>() };

Eclipse 说“无法创建 List 的通用数组”

ArrayList<String>[] nav = new ArrayList<String>[] { new ArrayList<String>() };

Eclipse 说“无法创建 ArrayList 的通用数组”

List<String>[] getListsOfStrings() {
    List<String> groupA = new ArrayList<String>();
    List<String> groupB = new ArrayList<String>();
    return new List<String>[] { groupA, groupB };
}

但我可以这样做:

List[] getLists() {
    return new List[] { new ArrayList(), new ArrayList() };
}

Eclipse 说 List 和 ArrayList 是原始类型,但它可以编译...

看起来很简单,为什么行不通?

最佳答案

好吧,generics tutorial回答你的问题。

The component type of an array object may not be a type variable or a parameterized type, unless it is an (unbounded) wildcard type.You can declare array types whose element type is a type variable or a parameterized type, but not array objects.

This is annoying, to be sure. This restriction is necessary to avoid situations like:

// Not really allowed.
List<String>[] lsa = new List<String>[10];
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
// Unsound, but passes run time store check
oa[1] = li;

// Run-time error: ClassCastException.
String s = lsa[1].get(0);

If arrays of parameterized type were allowed, the previous example would compile without any unchecked warnings, and yet fail at run-time. We've had type-safety as a primary design goal of generics.

关于Java 1.6 : Creating an array of List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5662394/

相关文章:

java - 使用 Math.round 舍入到小数点后一位?

java - 如何在java中使用流畅的接口(interface)和泛型来修复对象返回类型

java - 类新实例上的 Spring @Autowired

java - java中泛型的困惑

typescript 可选的通用属性

java - 泛型定义

Java 自定义树节点交换

java - while(true)loop 迫使我的应用程序在 Android 中崩溃

用于生成给定 JSON 字符串的 Java 类

java - 如何在 Struts 2 中使用 Ajax 调用获得成功结果后重定向到另一个 JSP