[英]Create a generic array accesing a single particular type
我想将泛型类型的ArrayList
转换为泛型类型的数组(相同的泛型类型)。 对于exaple我有ArrayList<MyGeneric<TheType>>
,我想获得MyGeneric<TheType>[]
。
我尝试使用toArray
方法并进行转换:
(MyGeneric<TheType>[]) theArrayList.toArray()
但这不起作用。 我的另一个选择是创建一个MyGeneric<TheType>
数组, 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>
是不兼容的类型。
这样做:
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-collection-here” 不是一个选项。
首先创建一个类型的数组,然后你应该调用:
<T> T[] toArray(T[] a)
以适当的顺序返回包含此列表中所有元素的数组(从第一个元素到最后一个元素); 返回数组的运行时类型是指定数组的运行时类型。
阅读规范: http : //docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray(T [])
如果您的数组比列表短,则该方法将分配并返回一个新数组; 如果您的数组比列表长,则数组中的其余项将设置为null。
-----------例子----------
ArrayList<MyGeneric<TheType>> list;
//......
MyGeneric<TheType>[] returnedArray = new MyGeneric[list.size()]; // You can't create a generic array. A warning for an error. Don't mind, you can suppress it or just ignore it.
returnedArray = list.toArray(returnedArray); // Cong! You got the MyGeneric<TheType>[] array with all the elements in the list.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.