Java List toArray(T[] a) implementation

后端 未结 5 1362
挽巷
挽巷 2021-01-04 13:26

I was just looking at the method defined in the List interface:

Returns an array containing all of the elements in this list in the correct order; the

5条回答
  •  既然无缘
    2021-01-04 13:41

    My guess is that if you already know the concrete type of T at the point you're calling toArray(T[]), it's more performant to just declare an array of whatever it is than make the List implementation call Arrays.newInstance() for you -- plus in many cases you can re-use the array.

    But if it annoys you, it's easy enough to write a utility method:

    public static  E[] ToArray(Collection c, Class componentType) {
        E[] array = (E[]) Array.newInstance(componentType, c.size());
        return c.toArray(array);
    }
    

    (Note that there's no way to write E[] ToArray(Collection c), because there's no way to create an array of E at runtime without a Class object, and no way to get a Class object for E at runtime, because the generics have been erased.)

提交回复
热议问题