簡體   English   中英

創建訪問單個特定類型的通用數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM