Java generics and Array's

前端 未结 5 1456
长发绾君心
长发绾君心 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:18

    Unfortunately there is no way to dynamically create an array of generic type in Java, because information related to generic type (E) is not carried at run-time, so there is no way to know what type of array to create.

    To solve the problem I would suggest a similar solution to the one used in collections library

    T[] java.util.List.toArray(T[] array)
    

    method. That is, instead of creating a new array inside your appendToArray function, pass it from outside. That is:

    public static  E[] appendToArray(E[] array, E item, E[] newArray) {
      ... your code ...
    }
    
    @Test
    public void test(){
      appendToArray(array, "b", new String[array.length+1]);
    }
    

    I know this does not looks as nice as other solutions, but it's type safe, and has better performance because it does not resort to reflection. For this very reason you are recommended to use

    T[] java.util.List.toArray(T[] array)
    

    method over it's reflection equivalent

    T[] java.util.List.toArray()
    

提交回复
热议问题