【发布时间】:2013-01-10 20:32:06
【问题描述】:
我想将泛型类型的ArrayList 转换为泛型类型数组(相同的泛型类型)。例如,我有ArrayList<MyGeneric<TheType>>,我想获得MyGeneric<TheType>[]。
我尝试使用toArray 方法和强制转换:
(MyGeneric<TheType>[]) theArrayList.toArray()
但这不起作用。我的另一个选择是创建一个MyGeneric<TheType> 的数组并一个接一个地插入arraylist 的元素,将它们转换为正确的类型。
但是我试图创建这个数组的一切都失败了。
我知道我必须使用Array.newInstance(theClass, theSize),但我如何获得MyGeneric<TheType> 的类?使用这个:
Class<MyGeneric<TheType>> test = (new MyGeneric<TheType>()).getClass();
不起作用。 IDE 声明 Class<MyGeneric<TheType>> 和 Class<? extends MyGeneric> 是不兼容的类型。
这样做:
Class<? extends MyGeneric> test = (new MyGeneric<TheType>()).getClass();
MyGeneric[] data = (MyGeneric[]) Array.newInstance(test, theSize);
for (int i=0; i < theSize; i++) {
data[i] = theArrayList.get(i);
}
return data;
在data[i] = ... 行引发ClassCastException。
我该怎么办?
注意:
我需要该数组,因为我必须将它与第三方库一起使用,因此“在此处使用 insert-the-name-of-the-collection-here”不是一个选项。
【问题讨论】:
标签: java arrays generics casting arraylist