Java 集合系列01-ArrayList 源码解析(JDK 1.8)

557 阅读4分钟

ArrayList 是一个动态数组,实现List, RandomAccess, Cloneable, java.io.Serializable 接口。

成员变量

   //初始容量大小
   private static final int DEFAULT_CAPACITY = 10;

    // 空ArrayList 实例
    private static final Object[] EMPTY_ELEMENTDATA = {};

    //默认大小的空ArrayList,当新增第一个元素时,扩容为DEFAULT_CAPACITY 
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    //真正存放数据的数组
    transient Object[] elementData; // non-private to simplify nested class access

    //elementData 数组大小
    private int size;

构造方法

    // 初始化指定大小的ArrayList
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    // 初始化空的ArrayList, 初始容量为10
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    // 根据集合初始化ArrayList
    public ArrayList(Collection<? extends E> 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;
        }
    }

新增

每次新增都会判断是否需要扩容,扩容规则:扩容为原来容量的1/2.

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = 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);
    }
    
    public void add(int index, E element) {
        rangeCheckForAdd(index);//越界检查

        ensureCapacityInternal(size + 1);  // 判断是否需要扩容
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);// 将index 的数据向后移动一位
        elementData[index] = element; // 插入数据
        size++;
    }
// 将集合中的元素添加到数组的末尾
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // 判断是否需要扩容
        System.arraycopy(a, 0, elementData, size, numNew); // 将a 中的所有元素放在数据的末尾
        size += numNew;
        return numNew != 0;
    }

删除

    public E remove(int index) {
        rangeCheck(index); //越界检查

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved); // 将数据前移,覆盖index 的数据
        elementData[--size] = null; // 置空,方便GC

        return oldValue;
    }
    // 查找remove 对象的index,在根据index 进行remove
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

    // 跳过越界检查,并且不反悔remove 的值,其余均同根据index remove 元素的方法
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

以下删除算法的思想是: 将elementData 中有,Collection 中没有的元素全部前移,后面置空。

   // 删除集合时,只会删除它们公共的元素
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    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;
    }

修改

    // 修改操作
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

查询

    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

面试常见问题

  • ArrayList 访问元素的时间复杂度是多少?为什么?

O(1)

原因:ArrayList 底层是数组存储,数组在内存中是连续的地址空间,可以使用O(1)去访问元素,时间效率很高。 ArrayList 实现RandomAccess 就代表其具有随机读写的能力。但是,ArrayList 空间效率不高,原因也是因为数组,因为ArrayList 在初始化后是一个空数组,空间效率100%,当新增第一个元素后,扩容DEFAULT_CAPACITY=10,此时,数据容量10,使用1,空间效率10%,所以ArrayList 空间效率不高。

  • ArrayList 的初始容量与扩容规则

默认容量10,默认扩容为原来容量的1/2,如果指定容量比原来容量的1/2 大,则扩容至指定容量。

  • ArrayList 查询与删除效率如何

ArrayList 查询效率很高,时间复杂度为O(1),原因是因为数组存储,时间效率高 删除效率很低,原因还是因为数组,删除的时候,涉及到数组的复制移动,相对低效。

  • ArrayList 与Vector 的区别

先来结果,后续上Vector 源码分析 Vector 内部也是数组实现,只是使用了synchronized 实现了线程安全;Vector扩容时是翻倍size,而ArrayList是扩容50%。

参考: www.cnblogs.com/skywang1234… juejin.cn/post/684490… juejin.cn/post/684490…