通用数组创建错误 [英] 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屋!
查看全文