细说JDK1.8下的ArrayList

最近在准备秋招,打算把自己看的Javase源码通过博客的方式记录下来,以便后面翻看

首先要说的是ArrayList, ArrayList作为开发中最常用到的集合类,在面试中也是经常会被问到它的底层实现,所以就让我们一起来揭开它的神秘面纱吧。

一 什么是ArrayList

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

从上面ArrayList的继承实现关系中,可以看到ArrayList实现了List,而我们知道List接口实现了Collection接口,所以 ArrayList也是一种用来存放对象的容器。同时还能看到ArrayList实现了Cloneable和Serialiable接口,证明它是可以被克隆和序列化的

二 ArrayList的成员变量

 private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 数组默认初始化容量为10
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空数组,当制定该ArrayList容量为0时,返回该数组
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     *默认空数组,这是jdk1.8之后新加入的,它与上面数组的区别是:该数组是默认返回的,
     *而上面是用户指定容量为0时返回的
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 存放元素的数组,被transient修饰
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * ArrayList当前元素的个数
     */
    private int size;

说明:从上面ArrayList的成员变量我们可以看出ArrayList底层是通过维护了一个数组来存放元素的,该数组的默认初始化容量为10,那么有人会说,那直接通过数组来存放元素就行了,实际上,ArrayList不同于数组,它是可以动态孔扩容的。还有一点,细心的同学可能会发现ArrayList底层维护的数组是被transient所修饰的,证明该数组是不可以被序列化的,而上面又说到ArrayList实现了Serialiable接口,岂不是反序列化后的ArrayList丢失了原先的元素?其实玄机在于ArrayList中的两个方法:writeObject和readObject,  ArrayList在序列化的时候会调用writeObject,直接将size和element写入ObjectOutputStream;反序列化时调用readObject,从ObjectInputStream获取size和element,再恢复到elementData。
       为什么不直接用elementData来序列化,而采用上诉的方式来实现序列化呢?原因在于elementData是一个缓存数组,它通常会预留一些容量,等容量不足时再扩充容量,那么有些空间可能就没有实际存储元素,采用上诉的方式来实现序列化时,就可以保证只序列化实际存储的那些元素,而不是整个数组,从而节省空间和时间。这里就不贴上他们的源码了,有兴趣可以自己去看一下。

三 ArrayList的构造器

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

    /**
     * 没有入参的构造器,可以看到数组是上文的DEFAULTCAPACITY_EMPTY_ELEMENTDATA成员变量
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 入参为集合的构造器
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray 可能返回的不是一个Object数组
            if (elementData.getClass() != Object[].class)
                //使用 Arrays.copy 方法拷创建一个 Object 数组
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

四  ArrayList的增删改查

接下来就是ArrayList的重头戏了,首先让我们来看添加方法:

    /**
     * 添加一个元素
     */
    public boolean add(E e) {
        //对数组容量进行调整
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        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 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;
        //新数组有元素,就返回 true
        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;
    }

可以看到,所有的添加方法都调用了ensureCapacityInternal()进行数组容量的调整,下面就让我们一起来看看这个方法:

//minCapacity为size+新添加的元素个数,即最小容量
private void ensureCapacityInternal(int minCapacity) {
        //调用了ensureExplicitCapacity和calculateCapacity两个方法
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

private static int calculateCapacity(Object[] elementData, int minCapacity) {
        //如果数组等于默认的空数组,则通过比较默认容量10和minCapacity的大小,返回那个大的
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }   
        //否则直接返回minCapacity
        return minCapacity;
    }
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // 容量不够,调用grow方法进行扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
 private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //新容量为老容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //如果新容量小于最小容量,则将最小容量赋值给新容量
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //如果新容量大于阈值
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            //最大容量可以是 Integer.MAX_VALUE
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity 一般跟元素个数 size 很接近,所以新建的数组容量为 newCapacity 更宽松些
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

说明:上面添加的代码有点多,有些人看起来可能会觉得很烦躁,所以i我简单的总结一下,首先我们ArrayList有四个添加元素的方法,当我们添加新的元素时,ArrayList底层的数组容量可能会不够,这时我们需要调用ensureCapacityInternal(int minCapacity)方法对数组的容量进行判断,如果不够就调用grow(int minCapacity)方法对数组进行扩容,新容量默认为老容量的1.5倍,如果老容量的1.5倍依然不够,则将最小容量作为新容量。

看完ArrayList的添加方法,修改和查询相对就容易多了,都是根据角标进行操作,直接上代码:

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

接着看删除方法: 

//根据角标删除一个元素    
public E remove(int index) {
        //查看是否角标越界
        rangeCheck(index);

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

        int numMoved = size - index - 1;
        if (numMoved > 0)
            //调用arraycopy将角标后的元素整体前移
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //将size最后一位清空,gc防止内存泄漏
        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
    }
 public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }
   //删除或者保留指定集合中的元素
private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    //使用两个变量,一个负责向后扫描,一个从 0 开始,等待覆盖操作
    int r = 0, w = 0;
    boolean modified = false;
    try {
        //遍历 ArrayList 集合
        for (; r < size; r++)
            //如果指定集合中是否有这个元素,根据 complement 判断是否往前覆盖删除
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        //发生了异常,直接把 r 后面的复制到 w 后面
        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;
}

    //清除整个ArrayList
    public void clear() {
        modCount++;

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

        size = 0;
    }

说明:看完删除方法都知道,删除完一个元素后还要进行数组的前移,所以删除的效率会比较慢,这也是我们如果经常用到添加修改的时候会用LinkedList而不用ArrayList的原因。

五  ArrayList的内部类

ArrayList中有两个内部类,分别是Itr和ListItr,他们都实现了Iterator接口,相信Iterator大家都不会陌生,迭代器嘛,通过游标来遍历集合的,具体没什么好讲的,看看代码就可以了:

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

可以看到在Itr和ListItr中的方法中都有一个 checkForComodification()的方法 ,因为ArrayList不是线程安全的,当我们通过Iterator遍历ArrayList时,可能有其他线程正在对ArrayList进行操作,这时候就会通过 checkForComodification()触发fail-fast机制。

六  总结

好的,看到这里,ArrayList就讲的差不多了,其实它还有一些方法我没有贴上来,因为这篇博客已经很长了,可能很多小伙伴都看睡着了,所以到最后我来总结一下。ArrayList底层是一个可以动态扩容的数组,初始化容量为10,每次扩容为原来的1.5倍(如果1.5倍不够,就使用最小容量作为新容量),ArrayList的特点是修改查询快,删除添加慢,刚好和LinkedList相反。

猜你喜欢

转载自blog.csdn.net/Rekeless/article/details/82555742
今日推荐