Convert a generic list to an array

前端 未结 13 1276
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 17:13

I have searched for this, but unfortunately, I don\'t get the correct answer.

class Helper {
    public static  T[] toArray(List list) {
           


        
13条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 17:41

    You can't instantiate a Generic type like you did here:

     T[] array = (T[]) new Object[list.size()];
    

    As, if T is bounded to a type, you're typecasting the new Object array to a bounded type T. I would suggest using List.toArray(T[]) method instead.

提交回复
热议问题