Convert a generic list to an array

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

    If you want to produce your method through brute force, and you can guarantee that you'll only call the method with certain restrictions, you can use reflection:

    public static  T[] toArray(List list) {
        T[] toR = (T[]) java.lang.reflect.Array.newInstance(list.get(0)
                                               .getClass(), list.size());
        for (int i = 0; i < list.size(); i++) {
            toR[i] = list.get(i);
        }
        return toR;
    }
    

    This approach has problems. As list can store subtypes of T, treating the first element of the list as the representative type will produce a casting exception if your first element is a subtype. This means that T can't be an interface. Also, if your list is empty, you'll get an index out of bounds exception.

    This should only be used if you only plan to call the method where the first element of the list matches the Generic type of the list. Using the provided toArray method is much more robust, as the argument provided tells what type of array you want returned.

提交回复
热议问题