List接口 — ArrayList类源码分析

一、ArrayList类 注释说明

  1. List 接口的大小可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。

  2. 在添加大量元素前,应用程序可以使用 ensureCapacity 操作来增加 ArrayList 实例的容量。这可以减少递增式再分配的数量。

  3. 注意,此实现不是同步的。如果多个线程同时访问一个 ArrayList 实例,而其中至少一个线程从结构上修改了列表,那么它必须 保持外部同步。(结构上的修改是指任何添加或删除一个或多个元素的操作,或者显式调整底层数组的大小;仅仅设置元素的值不是结构上的修改。)这一般通过对自然封装该列表的对象进行同步操作来完成。如果不存在这样的对象,则应该使用 Collections.synchronizedList 方法将该列表“包装”起来。这最好在创建时完成,以防止意外对列表进行不同步的访问:
    List list = Collections.synchronizedList(new ArrayList(...));

  4. 此类的 iterator 和 listIterator 方法返回的迭代器是快速失败的:在创建迭代器之后,除非通过迭代器自身的 remove 或 add 方法从结构上对列表进行修改,否则在任何时间以任何方式对列表进行修改,迭代器都会抛出 ConcurrentModificationException。


二、ArrayList类 源码

package java.util;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import sun.misc.SharedSecrets;


public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

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

    // 用于创建空数组实例
    private static final Object[] EMPTY_ELEMENTDATA = {};

    // 默认空数组,添加元素时比较两者的地址是否相同从而判断是否为第一次添加元素
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    // 存储数组列表元素的数组缓冲区.
    // 数组列表的容量是此数组缓冲区的长度
    // 添加第一个元素时elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
    transient Object[] elementData; // non-private to simplify nested class access

    // 数组的大小(它包含的元素数).
    private int size;

    /**
     * 构造具有指定初始容量的空列表
     * @param  initialCapacity  数组初始化大小
     * @throws IllegalArgumentException 如果指定初始容量为负值
     */
    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);
        }
    }

    /**
     * 构造初始容量为10的空列表
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 构造一个包含集合指定的元素的列表,返回集合迭代的顺序返回元素的顺序
     */
    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 {
            // 集合c为空的话,替换为空数组
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * 将数组空间的大小刚好等于数组元素的实际元素个数
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 如果需要的话,增加这个arraylist实例的容量,
     * 以确保它至少可以容纳由最小容量参数指定的元的数量
     */
    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);
        }
    }

  
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        // 判断该数组是否是使用无参构造方法构造的数组缓冲区
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            // 若所需的最小容量比默认容量小的话,则直接扩增容量为10
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        // 若使用其他构造方法创建的数组则返回所需的最小容量
        return minCapacity;
    }

    //  确保内部容量是否可以满足新增元素
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private void ensureExplicitCapacity(int minCapacity) {
        // 记录修改操作的次数
        modCount++;

        // 若所需的最小容量比现在的数组容量大,防止溢出,需要扩容数组
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 要分配的数组的最大大小
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 增加容量,以确保它至少可以容纳由最小容量参数指定的元素数。
     */
    private void grow(int minCapacity) {
        // 防溢出代码
        int oldCapacity = elementData.length;
        // 扩容大小 = 原数组大小 + 原数组大小/2
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        
        // 若是使用的无参构造函数创建的数组,则扩容的容量直接为默认容量10,
        // 若应用的其他函数则看情况
        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);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    // 返回数组中元素的数量
    public int size() {
        return size;
    }

    // 若数组为空,返回true
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 如果数组包含指定元素返回true
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * 返回此列表中指定元素的第一个匹配项的索引值,若不含则返回-1
     */
    public int indexOf(Object o) {
        // 先判断指定索引是否为null
        if (o == null) {
            // 正向遍历
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }


    // 返回此列表与指定元素匹配的最后一个项的索引值,不包含则返回-1
    public int lastIndexOf(Object o) {
        if (o == null) {
            // 逆向遍历
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }


     // 返回数组浅复制的实例
    public Object clone() {
        try {
            // 重新创建一个数组,与原数组无关
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    /**
     * 返回一个数组,其中包含此列表中的所有元素,
     * 并按正确的顺序排列(从第一个元素到最后一个元素)
     *
     * 返回的数组将是“安全的”,因为这个列表没有维护对它的引用。
     * (换句话说,此方法必须分配一个新数组)。因此,调用方可以自由地修改返回的数组。
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 返回的数组的运行时类型是指定数组的运行时类型
    */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        // 若参数的数组大小小于集合大小,则返回一个与集合大小相同的与参数数组同类型的数组
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
            
        System.arraycopy(elementData, 0, a, 0, size);
        // 如果传递的数组长度比size大,则将大于的位置设为null
        if (a.length > size)
            a[size] = null;
        return a;
    }

    // 位置存取操作
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    // 返回此列表指定位置的元素
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

    // 将列表中指定位置的元素替换为指定的元素
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        // 返回数组中索引位置的原来的值
        return oldValue;
    }

    // 添加指定元素在列表的末尾
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // modCount 将加1
        elementData[size++] = e;
        return true;
    }
    
    // 在列表中指定位置添加指定元素
    public void add(int index, E element) {
        // 先检查索引是否越界
        rangeCheckForAdd(index);

        // 判断容量确保能容下该元素
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // 若索引后面有元素的话,则将索引之后的元素都向后移1位
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

    // 在列表中移除指定位置的元素
    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);
        // size-1,并且将最后空出的元素设置为null
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
    
    // 如果存在的话,移除列表中第一次出现的指定的元素
    // 如果不存在指定的元素,在不发生改变.
    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;
    }

    // 私有删除方法 
    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
    }

    // 移除列表中的所有元素,所有元素都置为null
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

    // 按照指定集合的迭代器返回的顺序,将指定集合中的所有元素追加到此列表的末尾 
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        // 确保能够容下(size+numNew)个元素
        ensureCapacityInternal(size + numNew);  // Increments modCount
        // 将集合元素添加到列表末尾
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    // 将指定集合中的所有元素插入到此*列表中,从指定位置开始。
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount

        int numMoved = size - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

    // 从此列表中移除索引位于Fromindex包含和index之间的所有元素(独占)。
    // 将任何后续元素向左移动(减少它们的索引)
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    /**
     * 检查给定索引是否在范围内
     * 该方法不判断索引为负值,若索引为负值,数组访问时则会报错数组角标越界异常
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 构造索引异常详细信息
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    // 移除列表中包含集合中的所有元素
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    // 仅保留在*指定集合中包含的此列表中的元素。
    // 换句话说,从该列表中删除不包含在指定集合中的所有元素
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    // 通过第二个参数true或false来判断是保留还是删除所包含的元素
    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++)
                // 若complement为true : 则列表中包含集合中的元素,则
                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;
    }

三、扩展方法

    /**
     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
     * is, serialize it).
     *
     * @serialData The length of the array backing the <tt>ArrayList</tt>
     *             instance is emitted (int), followed by all of its elements
     *             (each an <tt>Object</tt>) in the proper order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;
        s.defaultWriteObject();

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;

        // Read in size, and any hidden stuff
        s.defaultReadObject();

        // Read in capacity
        s.readInt(); // ignored

        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            int capacity = calculateCapacity(elementData, size);
            SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

四、ArrayList中Iterator类

这部分的源码与Vector中的Iterator类源码类似,那个搞懂,这个就很容易理解
传送 : https://blog.csdn.net/qq_36852780/article/details/91187052#iterator

    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }


    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }


    public Iterator<E> iterator() {
        return new Itr();
    }


    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        Itr() {}

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * An optimized version of AbstractList.ListItr
     */
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

        public boolean hasPrevious() {
            return cursor != 0;
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor - 1;
        }

        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }

        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

五、ArrayList中subList类

返回此列表中指定的Fromindex(包含)和index(独占)之间的部分的视图。(如果Fromindex}和index相等,则返回的列表为空。)返回的列表由此列表支持,因此返回列表中的非结构化更改将反映在此列表中,反之亦然。返回的列表支持所有可选的列表操作。


其中返回的List拥有的功能,大多都是调用ArrayList中的方法,只是进行了封装.

ArrayList中拥有的方法,返回的List都有。



subList类用到的设计模式 : 装饰设计模式

对一组对象的功能进行增强.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值