The following snippet makes sense yet when I run this against my unit test.. I get a ClassCastException (Object can\'t be cast to String) on the line marked with \'>>>>\'.
As others have said, you should use Array.newInstance() to create an instance of the array of the correct type. What is more helpful is that you can get the component type you need out of the class of the original array.
Also, I simplified the copying by using System.arraycopy().
public static E[] appendToArray(E[] array, E item) {
E[] result = (E[])java.lang.reflect.Array.newInstance(array.getClass().getComponentType(), array.length+1);
System.arraycopy(array, 0, result, 0, array.length);
result[result.length-1] = item;
return result;
}
In Java 1.6+, you can just do this:
public static E[] appendToArray(E[] array, E item) {
E[] result = java.util.Arrays.copyOf(array, array.length+1);
result[result.length-1] = item;
return result;
}