casting ArrayList.toArray() with ArrayList of Generic Arrays

前端 未结 3 1851
梦毁少年i
梦毁少年i 2021-02-06 03:10

A difficult question which I\'m close to giving up all hope on. I\'m trying to make a function, but am having problems getting ArrayList.toArray() to return the ty

3条回答
  •  悲哀的现实
    2021-02-06 03:56

    You can't create an array of a generic type parameter. The simple reason is the fact that java usually erases the generic type information at runtime so the runtime has no idea what T is (when T is a generic type parameter).

    So the solution is to actually get a hold of the type information at runtime. Usually this is done by passing around a Class type parameter but in this case you can avoid that:

    @peter's answer looks good and i would use it :).

    return (T[]) list.toArray(Array.newInstance(one.getClass(), list.size()));
    

提交回复
热议问题