JDK源码解析之ArrayList

 一、ArrayList简介

       ArrayList在我们工作中的使用率非常高,它是个数组队列,相当于一个动态数组,相比于JAVA数组而言它的容量可以动态增长,而且提供了很多方法方便于我们使用, 它继承于 AbstractList ,实现了List 、RandomAccess 、Cloneable 、java.io.Serializable 接口。

      ArrayList 继承了 AbstractList ,实现了List 接口, 提供了增删改以及遍历等功能

      ArrayList 实现了 RandomAccess ,表明其支持快速的随机访问

      ArrayList 实现了Cloneable接口,覆盖了clone方法,表明其可以被克隆

      ArrayList 实现了java.io.Serializable 接口,表明其可以被序列化


 二、ArrayList的属性(JDK 1.8)

    

    

以上是ArrayList的属性:

    serialVersionUID : 实现了java.io.Serializable 接口后生成的序列化号

    DEFAULT_CAPACITY : 默认的数组容量

    EMPTY_ELEMENTDATA : 空数组

    DEFAULTCAPACITY_EMPTY_ELEMENTDATA : 默认空数组

    elementData: elementData是ArrayList的重要属性之一,用于保存添加到ArrayList中的元素

    size : 用于统计保存到ArrayList中的元素有多少个


 三、 构造方法

    ArrayList的构造方法有三个如下:

  

  

  


四、方法源码解析

  

    // 将容器的容量 = 元素的数量(size)
    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);
        }
    }
    // 增加此ArrayList实例的容量,以确保它至少能够容纳最小容量参数指定的元素数。
    private void ensureCapacityInternal(int minCapacity) {
        //如果当前的elementData为空的话,则在传进来的容量和默认容量中取最大的
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }
    // 判断新的容量是否大于数组的容量,是的话则扩大数组容量
    private void ensureExplicitCapacity(int minCapacity) {
        // 数组结构的修改次数 + 1
        modCount++;  

        // 判断新的容量是否大于数组的容量,是的话则扩大数组容量
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    // 定义最大的数组容量 2147483647 - 8
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    // 扩大数组的容量 新的容量 = 旧容量 + 旧容量 \ 2
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1); // >> 1 右移1位 ==oldCapacity \ 2 
        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;
    }

    // 判断容器是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    // 判断容器内是否包含某个元素, 有则返回true 无 false
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    // 判断某个元素在容器中数组的下标,如果该元素不存在则返回 -1
    public int indexOf(Object o) {
        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);
        }
    }

    //将容器转为Object数组
    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);
        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);  // 确保容器容量
        elementData[size++] = e; 
        return true;
    }

    //往某个下标添加元素,如果该下标已有元素,则将该元素以及后面的元素往后移
    public void add(int index, E element) {
        // 判断下标是否越界
        rangeCheckForAdd(index); 

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        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);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

    // 通过对象移除元素,如果该容器中不存在该对象则返回false,否则返回true
    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
    }

    // 清除该容器的元素
    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;
        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;
    }

    // 移除掉两个下标之间的元素
    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));
    }

    // 检查下标是否大于容器元素个数或者小于0,如果大于则抛出下标越界
    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);
    }
   // 批量移除元素
    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;
    }

以上是 jdk 1.8 中的源码,跟 1.8 之前的版本有些不同

猜你喜欢

转载自blog.csdn.net/qq_36712034/article/details/76690984