ArrayList

ArrayList

    /**
     * Increases the capacity of this <tt>ArrayList</tt> instance, if
     * necessary, to ensure that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     *
     * @param   minCapacity   the desired minimum capacity
     */
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }
//这段代码有点绕,当elementData为DEFAULTCAPACITY_EMPTY_ELEMENTDATA时,minExpand为DEFAULT_CAPACITY
//其他为0
//应该就是,当且仅当无参构造,且没有存放任何数据时候,minExpand为10,其他为0.
//设计思路应该是,如果你无参构造,一定确保你能放10个,其他构造,就按照你传入的算。
//举个例子,无参构造,没有放任何数据,想确保3个,并不会进入ensureExplicitCapacity
//无参构造,放入过数据,想确保3个,那就进入ensureExplicitCapacity
//有参构造,会进入ensureExplicitCapacity
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
//批量删除,传入true的时候,就是retainAll
//finally段有一个r!=size,如果正常,是不会r!=size的,只有报错才会出现r!=size
//这段就是如果报错了,把剩下没有处理的原封不动的拷贝进去。
//如果第一次调用contains报错,那处理完之后,w==size,如果是中间出错呢?
//好吧,中间出错后面也正常处理……
//w!=size就是存在有的数据并没有被拷贝(或者数组里移动)