casting ArrayList.toArray() with ArrayList of Generic Arrays

前端 未结 3 1850
梦毁少年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:43

    toArray() always returns an object array.

    To return an array of a specific type, you need to use toArray(Object[]).

    To provide the correct type for the array argument, you need to use the specific class or in this case use reflections.

    try

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

提交回复
热议问题