Convert a generic list to an array

前端 未结 13 1286
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  Happy的楠姐
    2020-12-05 17:34

    public static  T[] toArray(Collection c, T[] a) {
        return c.size()>a.length ?
            c.toArray((T[])Array.newInstance(a.getClass().getComponentType(), c.size())) :
            c.toArray(a);
    }
    
    /** The collection CAN be empty */
    public static  T[] toArray(Collection c, Class klass) {
        return toArray(c, (T[])Array.newInstance(klass, c.size()));
    }
    
    /** The collection CANNOT be empty! */
    public static  T[] toArray(Collection c) {
        return toArray(c, c.iterator().next().getClass());
    }
    

提交回复
热议问题