通用阵列创建错误 [英] Generic array creation error
本文介绍了通用阵列创建错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图做这样的事情: -
I am trying do something like this:-
public static ArrayList<myObject>[] a = new ArrayList<myObject>[2];
myObject的是一类。我收到此错误: - 通用阵列的创建(箭头指向新的。)
myObject is a class. I am getting this error:- Generic array creation (arrow is pointing to new.)
推荐答案
您不能有泛型类的数组。 Java的根本不支持它。
You can't have arrays of generic classes. Java simply doesn't support it.
您应该考虑使用一个集合,而不是一个数组。例如,
You should consider using a collection instead of an array. For instance,
public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>();
另一个变通方法是创造这样一个辅助类
Another "workaround" is to create an auxilliary class like this
class MyObjectArrayList extends ArrayList<MyObject> { }
,然后创建 MyObjectArrayList
的数组。
下面是为什么这是不是在允许一个好文章语言。文章给出是否被允许的会发生什么,下面的例子:
Here is a good article on why this is not allowed in the language. The article gives the following example of what could happen if it was allowed:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
这篇关于通用阵列创建错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文