How to properly return generic array in Java generic method?

前端 未结 3 393
逝去的感伤
逝去的感伤 2021-02-03 12:09

I have below generic method that returns a generic array:

public static  T[] genericMethod1(List input) {
    T[] res = (T[]) new Object[input.s         


        
3条回答
  •  故里飘歌
    2021-02-03 12:14

    Another way is to do it like in java.util.ArrayList.toArray(T[]). You pass the type of Array to that Method, if it's big enough it will be reused, otherwise an new Array is generated.

    Example:

        List intList = new ArrayList<>();
        intList.add(Integer.valueOf(1));
        intList.add(Integer.valueOf(2));
        intList.add(Integer.valueOf(3));
        Integer[] array = intList.toArray(new Integer[] {});
        System.out.println(Arrays.toString(array));//Will Print [1, 2, 3]
    

    Implementation of ArrayList.toArray(T[]) see here.

提交回复
热议问题