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.
Create an array of your type first, then you should call:
Read the specification:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray(T%5B%5D)
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 ———-