通用列表数组 [英] Array of Generic List
问题描述
我正在使用泛型和数组,似乎下面的代码编译得很好,
I am playing with Generic and arrays, it seems the following code compiles fine,
ArrayList<Key> a = new ArrayList<Key>();
但是编译器抱怨这个,
ArrayList<Key>[] a = new ArrayList<Key>[10];
通过阅读 stackoverflow 中的帖子,我有点明白这是由于类型擦除造成的,我可以通过使用来修复它,
By reading post in stackoverflow, I sort of understand that this is due to Type Erasure and I can fix it by using,
ArrayList<Key>[] a = (ArrayList<Key> []) new ArrayList[10];
或列表列表
ArrayList<ArrayList<Key>> b = new ArrayList<ArrayList<Key>>();
但我无法弄清楚幕后的原因.特别是,为什么第二个是非法的,因为第一个是完全可以的.以及为什么编译器不抱怨列表的列表.
But I can't figure out the reason behind the scene. Especially, why the second one is illegal given the first one is perfectly OK. And why the compiler does not complain about the list of list.
推荐答案
不能有数组,因为数组需要原始类型.您在第二个实例中对它进行类型转换,这使其适合定义的类型,因此是合法的(但是,它无法推断).列表的列表是合法的,因为 ArrayList
不是数组.
You can't have an array, because an array requires a raw type. You typecast it in the second instance, which makes it fit the defined type, and is therefore legal (however, this is impossible for it to infer). The list of list is legal as ArrayList
isn't an array.
阅读官方教程 了解更多详情.
数组对象的组件类型不能是类型变量或参数化类型,除非它是(无界)通配符类型.您可以声明元素类型为类型变量或参数化类型,但不是数组对象.这很烦人,这是肯定的.此限制是必要的,以避免出现以下情况:
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:
List<String>[] lsa = new List<String>[10]; // not really allowed
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[1] = li; // unsound, but passes run time store check
String s = lsa[1].get(0); // run-time error - ClassCastException
如果允许参数化类型的数组,则上面的示例将在没有任何未经检查的警告的情况下编译,但在运行时失败.
If arrays of parameterized type were allowed, the example above would compile without any unchecked warnings, and yet fail at run-time.
教程接着说以下内容:
由于类型变量在运行时不存在,所以无法确定实际的数组类型是.解决这些限制的方法是使用类文字作为运行时类型标记
Since type variables don’t exist at run time, there is no way to determine what the actual array type would be. The way to work around these kinds of limitations is to use class literals as run time type tokens
这篇关于通用列表数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!