/** * 传入一个集合对象 * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ publicArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { //不同的集合其toArray()方法实现不一样,数组有可能不是Object[].class,需要使用Arrays的复制方法处理一下 if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { this.elementData = EMPTY_ELEMENTDATA; } }
//如果添加数据时需要的最小容量已经大于elementData的长度了,调用grow方法进行扩容 if (minCapacity - elementData.length > 0) grow(minCapacity); }
privatevoidgrow(int minCapacity) { // overflow-conscious code intoldCapacity= elementData.length; intnewCapacity= oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }