Java generics and Array's

前端 未结 5 1467
长发绾君心
长发绾君心 2020-12-22 08:34

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 \'>>>>\'.

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-22 09:02

    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;
    }
    

提交回复
热议问题