ArrayList (jdk1.8)源码分析

概述

一首古诗句说的好,书中自有黄金屋。作为一个有追求的程序员,若想写好代码,则必须阅读好的源代码,并总结吸收其精髓。第一次写源码分析的文章,大家多多包涵。

ArrayList 类的继承关系图

这里写图片描述
说明:
ArrayList 实现了Iterable接口,说明该类可以通过迭代器遍历他。
ArrayList 实现了Collection接口,说明该类具有集合常规方法操作。
ArrayList 实现了List接口,说明该类具有线性表操作方法。
ArrayList实现了RandomAccess接口,说明该类可以通过index快速访问元素。
ArrayList实现了Cloneable接口,说明该类具有clone方法。
ArrayList实现了Serializable接口,说明该类可以进行序列化。

ArrayList 成员变量分析
    //该变量用于类的序列化标识id 
private static final long serialVersionUID = 8683452581122892189L;
    // elementData 为一个数组,是ArrayLIst真正存放数据的数据结构。
private transient Object[] elementData;
     // size ArrayList中元素个数(标识数组中真正存在元素的个数,非数组真正的长度)。
private int size;
ArrayList 常用方法分析
构造方法
//指定数组初始化长度构造方法
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
//ArrayList ,默认构造函数,会初始化elementData为10个长度的object数组;
    public ArrayList() {
        this(10);
    }
//也可以通过传入一个集合构造一个该集合元素的Arraylist(调用Arrays.copy实现数组copy)。
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }
增加元素方法
//向list尾部添加一个元素
    public boolean add(E e) {
    //确定当前数组容量是否够用,若不够用则扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
//向list指定位置添加一个元素
    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 boolean addAll(Collection<? extends E> c) {
    //获取待加入集合元素数组
        Object[] a = c.toArray();
        int numNew = a.length;
        //校验是否需要数组扩容
        ensureCapacityInternal(size + numNew);  // Increments modCount
        //调用native方法将数组copy到指定区域位置
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }
//向容器指定位置加入一个集合的元素(从index开始)
    public boolean addAll(int index, Collection<? extends E> c) {
    //校验index是否在指定范围
        rangeCheckForAdd(index);
    //获取待加入集合元素数组
        Object[] a = c.toArray();
        int numNew = a.length;
         //确定当前数组容量是否够用,若不够用则扩容
        ensureCapacityInternal(size + numNew);  // Increments modCount

        int numMoved = size - index;
        //如果index不是数组最后一个元素索引,将原先list中index到size之间的数据平移到index+numNew位置开始到集合末尾的位置
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
//将待加入集合数组元素copy到elementData指定index位置开始后的数据段中
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

//确认容量是否需要扩容
    private void ensureCapacityInternal(int minCapacity) {
        //modCount 自增标识list内容改变,(迭代器遍历会通过此变量判断数据是否改变)。
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);//若数组容器不够,则执行grow 函数扩容
    }

 //该变量用来标识数组长度是否快到溢出状态
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//真正的扩容函数
    private void grow(int minCapacity) {
        // overflow-conscious code
        //记录之前数组长度
        int oldCapacity = elementData.length;
        //计算新数组长度,为原来数组长度的1.5倍(扩容长度)
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //数组长度超过int 最大值,则数组不能扩容
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
            //数组扩容长度大于int最大值-8 则执行hugeCapacity函数超过int最大值抛出内存溢出异常,否则扩容到int最大值
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        //通过Arrays.copyOf复制移动数组
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
    //内存溢出
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
            //int最大值容量或最大值容量-8
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    //校验索引是否超出界限
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

方法执行流程:

这里写图片描述

查找遍历方法

//是否包含此元素
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
//从头遍历循环若找到指定元素,则返回下标(元素可为null),找不到返回-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;
    }
//访问数组某个索引的元素
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

  //获取指定索引的元素
    public E get(int index) {
    //校验索引范围
        rangeCheck(index);

        return elementData(index);
    }

 //校验索引返回,超出size则抛出IndexOutOfBoundsException异常
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    //获取指定索引开始的,list迭代器
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

   //获取从list头部开始遍历的,list待定器
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

   //获取list 老版本迭代器
    public Iterator<E> iterator() {
        return new Itr();
    }

   //旧版本迭代器,实现类
    private class Itr implements Iterator<E> {
    //next元素下标索引
        int cursor;       // index of next element to return
     //当前迭代器元素内容,用于删除List元素
        int lastRet = -1; // index of last element returned; -1 if no such
     //该变量为了记录,获取迭代器时候,list修改状态的(List不支持多线程
     //当list遍历的时候,其他线程修改list,会通过该变量,抛出异常)。
        int expectedModCount = modCount;
//时候还有元素
        public boolean hasNext() {
            return cursor != size;
        }
//获取下个元素
        @SuppressWarnings("unchecked")
        public E next() {
        //校验List是否修改过
            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();
            }
        }
        //校验状态是否变化过
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * An optimized version of AbstractList.ListItr
     */
     //优化版本的迭代器 可以获取指定list遍历起点的的迭代器 也可以双向遍历
    private class ListItr extends Itr implements ListIterator<E> {
    //指定迭代器起始索引的构造方法
        ListItr(int index) {
            super();
            cursor = index;
        }
//是否有前向元素
        public boolean hasPrevious() {
            return cursor != 0;
        }
//获取next元素索引
        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();
            }
        }
    }

由以上源码可以知道,我们可以直接通过索引获取list中的元素。也可以通过for循环遍历获取list元素。也可以通过两种迭代器遍历list元素。

删除方法
//通过索引移除元素
    public E remove(int index) {
        rangeCheck(index);

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

        int numMoved = size - index - 1;
        //不是最后一个元素,进行数组平移copy
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // 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) {
                //快速通过索引删除,不用校验index
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
             //寻找索引
                if (o.equals(elementData[index])) {
                //快速通过索引删除,不用校验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; // Let gc do its work
    }

//遍历将清楚List
    public void clear() {
        modCount++;

        // Let gc do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }
//移除指定范围的list元素
protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // Let gc do its work
        int newSize = size - (toIndex-fromIndex);
        while (size != newSize)
            elementData[--size] = null;
    }

   //索引校验
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    //移除指定集合内的元素
      public boolean removeAll(Collection<?> c) {
        return batchRemove(c, false);
    }
    //只保留指定集合中的元素
     public boolean retainAll(Collection<?> 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) {
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
其他方法介绍
//自定义序列化方法
    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 array length
        s.writeInt(elementData.length);

        // 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();
        }

    }

 //自定义反序列化方法
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in size, and any hidden stuff
        s.defaultReadObject();

        // Read in array length and allocate array
        int arrayLength = s.readInt();
        Object[] a = elementData = new Object[arrayLength];

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

ArrayList 底层通过数组实现。
ArrayList 在插入数据,数组长度不够,数组会出现扩容,扩容长度为原来的1.5倍,扩容的过程会出现数组内容copy,更大内存数组生成,比较耗时。
ArrayList 删除数据的时候,会产生数组平移copy,比较耗时。
ArrayList 查找数据,比较快,可以直接通过下标索引获取数据。
ArrayList 不支持多线程,通过迭代器遍历的时候,如果有其他线程删除或新增元素,会抛出 ConcurrentModificationException()异常。
ArrayList 遍历删除元素,最好通过迭代器实现。ArrayList有两种迭代器,一种只能单向迭代,最新的一种可以双向,并且指定迭代范围。
ArrayList 重写了序列化方法。
希望对您有所帮助!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值