Convert a generic list to an array

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

    The problem is the component type of the array that is not String.

    Also, it would be better to not provide an empty array such as new IClasspathEntry[0]. I think it is better to gives an array with the correct length (otherwise a new one will be created by List#toArray which is a waste of performance).

    Because of type erasure, a solution is to give the component type of the array.

    Example:

    public static  C[] toArray(Class componentType, List list) {
        @SuppressWarnings("unchecked")
        C[] array = (C[])Array.newInstance(componentType, list.size());
        return list.toArray(array);
    }
    

    The type C in this implementation is to allow creation of an array with a component type that is a super type of the list element types.

    Usage:

    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("abc");
    
        // String[] array = list.toArray(new String[list.size()]); // Usual version
        String[] array = toArray(String.class, list); // Short version
        System.out.println(array);
    
        CharSequence[] seqArray = toArray(CharSequence.class, list);
        System.out.println(seqArray);
    
        Integer[] seqArray = toArray(Integer.class, list); // DO NOT COMPILE, NICE !
    }
    

    Waiting for reified generics..

提交回复
热议问题