集合List添加集合,复制内容的方法

2017-12-28  本文已影响0人  qiwx

第一种:AddAll():

ArrayList 的AddAll()方法如下:

public boolean addAll(Collection c) {

    Object[] a = c.toArray();

    int numNew = a.length;

    ensureCapacityInternal(size + numNew);  // Increments modCount

    System.arraycopy(a, 0, elementData, size, numNew);//核心代码

    size += numNew;

    return numNew != 0;

}

第二种:ArrayList(List A)

public ArrayList(Collection c) {

    elementData = c.toArray();

    if ((size = elementData.length) != 0) {

        // c.toArray might (incorrectly) not return Object[] (see 6260652)

        if (elementData.getClass() != Object[].class)

            elementData = Arrays.copyOf(elementData, size, Object[].class);//核心代码

    } else {

        // replace with empty array.

        this.elementData = EMPTY_ELEMENTDATA;

    }

}

上一篇 下一篇

猜你喜欢

热点阅读