为什么我不能创建一个 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/