如何創(chuàng)建泛型數(shù)組?我不明白泛型和數(shù)組之間的聯(lián)系。我可以用泛型類型創(chuàng)建數(shù)組引用:private E[] elements; //GOOD但不能創(chuàng)建具有泛型類型的數(shù)組對(duì)象:elements = new E[10]; //ERROR但它起作用了:elements = (E[]) new Object[10]; //GOOD
3 回答

蝴蝶刀刀
TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
LinkedList<T>#toArray(T[])
:
public <T> T[] toArray(T[] a) { if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); int i = 0; Object[] result = a; for (Node<E> x = first; x != null; x = x.next) result[i++] = x.item; if (a.length > size) a[size] = null; return a;}
Array.newInstance(Class, int)
int

翻過高山走不出你
TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
new E[10]
new Object[10]
.
E
創(chuàng)建對(duì)象數(shù)組并將其轉(zhuǎn)換為 E[]
數(shù)組,或 使用 Array.newInstance(類組件類型,int長(zhǎng)度) 若要?jiǎng)?chuàng)建傳入的類型數(shù)組的實(shí)際實(shí)例,請(qǐng)執(zhí)行以下操作 componentType
裝備。
添加回答
舉報(bào)
0/150
提交
取消