Your code throws that exception because it's actually giving you an array of type Object. Maurice Perry's code works, but the cast to K[ ] will result in a warning, as the compiler can't guarantee type safety in that case due to type erasure. You can, however, 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 guaranteed type safety. How this works is explained in depth in my answer to a similar question from a while back.