Java 1.6 : Creating an array of List<T>

标签 java generics

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

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

Eclipse 提示“无法创建列表的通用数组”

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/15856029/

相关文章:

java - 如何使用文件 channel 和字节缓冲区将 double 写入文件?

java - 无法实例化 AbstractSet 类

java接口(interface)输入参数从基类扩展

typescript - 如何使用 Typescript 将类中的变量初始化为其通用值

java - 泛型 - 集合中的 Java 集合

java - 错误 org.json.JSONObject 无法转换为 JSONArray

java - Eclipse 内部错误 "Polling news feeds"

java - 无需解压即可预览 .7z 内容和子文件夹

generics - 返回映射的通用函数

javac 找不到源文件