Convert a generic list to an array

前端 未结 13 1284
隐瞒了意图╮
隐瞒了意图╮ 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:49

    This is due to type erasure. The generics are removed in compilation, thus the Helper.toArray will be compiled into returning an Object[].

    For this particular case, I suggest you use List.toArray(T[]).

    String[] array = list.toArray(new String[list.size()]);
    

提交回复
热议问题