Your code throws this exception because it actually gives you an array of type Object . Maurice Perry's code works, but casting to K[ ] will result in a warning, since the compiler cannot guarantee type safety in this case due to type erasure. However, you can do the following.
import java.util.ArrayList; import java.lang.reflect.Array; public class ExtremeCoder<K> extends ArrayList<K> { public K[ ] toArray(Class<K[ ]> clazz) { K[ ] result = clazz.cast(Array.newInstance(clazz.getComponentType( ), this.size( ))); int index = 0; for(K k : this) result[index++] = k; return result; } }
This will give you an array of the type you want with a safe type guarantee. How this works is explained in detail in my answer with a similar question some time ago.
source share