I have a generic (I’m not too sure if that’s the correct terminology..) method that adds an object to the an array.
@SuppressWarnings("unchecked")
public static <T>T[] appendArray(T[] a, T b)
{
T[] temp = (T[])new Object[a.length + 1];
System.arraycopy(a, 0, temp, 0, a.length);
temp[a.length] = b;
return temp;
}
In Eclipse, this code gives me no errors, no warnings (except for the suppressed “unchecked” warning), and, it seems to me, that this should work.. However, when I attempt to call this method with something such as..
Integer[] a=new Integer[]{1,2,3};
Integer b=4;
a = appendArray(a, b);
It gives me a ClassCastException on, in this case, line 3 of the 2nd snippet of code I posted. The error says, [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; I neither see, nor understand why it would be doing this.. I mean, I’m using generics, so why would it there be an Object[] other than the one which I cast to type T during instantiation? And if it is the one at line number 4 (in the 1st bit of code, of course), why isn’t the exception being thrown there rather than at line 3 of the 2nd bit of code?
Instead of using
System.arraycopy, useArrays.copyOf, which instantiates the array as the generic type.