Bakuriu
Bakuriu

Reputation: 101919

Create a generic array accesing a single particular type

I want to convert an ArrayList of a generic type to an array of generic types(the same generic type). For exaple I have ArrayList<MyGeneric<TheType>> and I want to obtain MyGeneric<TheType>[].

I tried using the toArray method and casting:

(MyGeneric<TheType>[]) theArrayList.toArray()

But this does not work. My other option is to create an array of MyGeneric<TheType> and insert one by one the elements of the arraylist, casting them to the correct type. But Everything I tried to create this array failed.

I know I have to use Array.newInstance(theClass, theSize) but how do I obtain the class of MyGeneric<TheType>? Using this:

Class<MyGeneric<TheType>> test = (new MyGeneric<TheType>()).getClass();

Does not work. The IDE states that Class<MyGeneric<TheType>> and Class<? extends MyGeneric> are incompatible types.

Doing this:

    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;

Raises a ClassCastException at the line data[i] = ....

What should I do?

Note:

I need the array because I have to use it with a third-party library so "use a insert-the-name-of-the-collection-here" is not an option.

Upvotes: 1

Views: 123

Answers (1)

shuangwhywhy
shuangwhywhy

Reputation: 5625

Create an array of your type first, then you should call:

<T> T[]   toArray(T[] a)

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Read the specification: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray(T[])

If your array is shorter than the list, a new array will be allocated and returned by the method; if your array is longer than the list, the rest items in the array will be set to null.

----------- example ----------

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.

Upvotes: 3

Related Questions