Hello,
I found that I can create a generic array and fill it with some data,
but I cannot return it. What is going on?
The example below throws ClassCastException:
public class Test {
public <T> T[] test(T val,int n) {
T[] array = (T[]) new Object[n];
for(int i=0;i<n;i++) {
array[i] = val;
System.out.println("inserted "+array[i]);
}
return array;
}
public static void main(String[] args) {
Test tt = new Test();
String[] ss = tt.test("empty",3);
for(String s: ss) System.err.println(s);
}
}
Tom Hawtin - 08 May 2007 18:31 GMT
> I found that I can create a generic array and fill it with some data,
> but I cannot return it. What is going on?
You're not creating a generic array. You are creating a non-generic
array and then incorrectly casting it.
Given a Class<T> (T will not be generic itself), you can create an array
of T[] using java.lang.reflect.Array.newInstance.
Given an existing T[] you can get Class<T[]> through Object.getClass.
Form Class<T[]> you can get a Class<?> that, although having a wildcard,
is the same instance as T.class. You can create an array with the
correct runtime type from this, and then do an unsafe cast to correct
the compile-time type.
Better still, avoid using arrays of references and stick with the likes
of List<T>.
Tom Hawtin