源码分析之ArrayList

概念

ArrayList是咱们经常使用的集合类,是基于数组实现的。不一样于数组的是ArrayList能够动态扩容。java

类结构

ArrayListJava集合框架List接口的一个实现类。提供了一些操做数组元素的方法。数组

实现List接口同时,也实现了 RandomAccess, Cloneable, java.io.Serializable安全

ArrayList继承与AbstractList多线程

ArrayList类图

类成员

elementData

transient Object[] elementData;复制代码

elementData是用于保存数据的数组,是ArrayList类的基础。并发

elementData是被关键字transient修饰的。咱们知道被transient修饰的变量,是不会参与对象序列化和反序列化操做的。而咱们知道ArrayList实现了java.io.Serializable,这就代表ArrayList是可序列化的类,这里貌似出现了矛盾。框架

ArrayList在序列化和反序列化的过程当中,有两个值得关注的方法:writeObjectreadObjectdom

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

    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
            ensureCapacityInternal(size);

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

writeObject会将ArrayList中的sizeelement数据写入ObjectOutputStreamreadObject会从ObjectInputStream读取sizeelement数据。ide

之因此采用这种序列化方式,是出于性能的考量。由于ArrayListelementData数组在add元素的过程,容量不够时会动态扩容,这就到可能会有空间没有存储元素。采用上述序列化方式,能够保证只序列化有实际值的数组元素,从而节约时间和空间。函数

size

private int size;复制代码

sizeArrayList的大小。性能

DEFAULT_CAPACITY

/** * Default initial capacity. */
    private static final int DEFAULT_CAPACITY = 10;复制代码

ArrayList默认容量是10。

构造函数

ArrayList提供了2个构造函数ArrayList(int initialCapacity)ArrayList()

使用有参构造函数初始化ArrayList须要指定初始容量大小,不然采用默认值10。

add()方法

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }复制代码

add元素以前,会调用ensureCapacityInternal方法,来判断当前数组是否须要扩容。

private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            // 若是elementData为空数组,指定elementData最少须要多少容量。
            // 若是初次add,将取默认值10;
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }

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

        // overflow-conscious code
        // elementData容量不足的状况下进行扩容
        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);
    }复制代码
  • grow方法中能够看出,ArrayListelementData数组如遇到容量不足时,将会把新容量newCapacity设置为 oldCapacity + (oldCapacity >> 1)。二进制位操做>> 1等同于/2的效果,扩容致使的newCapacity也就设置为原先的1.5倍。

  • 若是新的容量大于MAX_ARRAY_SIZE。将会调用hugeCapacityint的最大值赋给newCapacity。不过这种状况通常不会用到,不多会用到这么大的ArrayList

在确保有容量的状况下,会将元素添加至elementData数组中。

add(int index, E element) 方法

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++;
    }复制代码

带有indexadd方法相对于直接add元素方法会略有不一样。

  • 首先会调用rangeCheckForAdd来检查,要添加的index是否存在数组越界问题;
  • 一样会调用ensureCapacityInternal来保证容量;
  • 调用System.arraycopy方法复制数组,空出elementData[index]的位置;
  • 赋值并增长size

remove(int index) 方法

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;
    }复制代码

ArryList提供了两个删除List元素的方法,如上所示,就是根据index来删除元素。

  • 检查index是否越界;
  • 取出原先值的,若是要删除的值不是数组最后一位,调用System.arraycopy方法将待删除的元素移动至elementData最后一位。
  • elementData最后一位赋值为null。

remove(Object o) 方法

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(Object o)是根据元素删除的,相对来讲就要麻烦一点:

  • 当元素o为空的时候,遍历数组删除空的元素。
  • 当元素o不为空的时候,遍历数组找出于o元素的index,并删除元素。
  • 若是以上两步都没有成功删除元素,返回false

modCount

addremove过程当中,常常发现会有modCount++或者modCount--操做。这里来看下modCount是个啥玩意。

modCount变量是在AbstractList中定义的。

protected transient int modCount = 0;复制代码

modCount是一个int型变量,用来记录ArrayList结构变化的次数。

modCount起做用的地方是在使用iterator的时候。ArrayListiterator方法。

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;

        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();
        }
    }复制代码

iterator方法会返回私有内部类Itr的一个实例。这里能够看到Itr类中不少方法,都会调用checkForComodification方法。来检查modCount是够等于expectedModCount。若是发现modCount != expectedModCount将会抛出ConcurrentModificationException异常。

这里写一个小例子来验证体会下modCount的做用。简单介绍一下这个小例子:准备两个线程t1t2,两个线程对同一个ArrayList进行操做,t1线程将循环向ArrayList中添加元素,t2线程将把ArrayList元素读出来。

Test类:

public class Test {

    List<String> list = new ArrayList<String>();


    public Test() {

    }


    public void add() {

        for (int i = 0; i < 10000; i++) {
            list.add(String.valueOf(i));
        }

    }

    public void read() {

        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    }复制代码

t1线程:

public class Test1Thread implements Runnable {

    private Test test;

    public Test1Thread(Test test) {
        this.test = test;
    }

    public void run() {

        test.add();

    }复制代码

t2线程:

public class Test2Thread implements Runnable {

    private Test test;

    public Test2Thread(Test test) {
        this.test = test;
    }


    public void run() {
        test.read();
    }
}复制代码

main

public static void main(String[] args) throws InterruptedException {

        Test test = new Test();
        Thread t1  = new Thread(new Test1Thread(test));
        Thread t2  = new Thread(new Test2Thread(test));

        t1.start();
        t2.start();

    }复制代码

执行这个mian类就会发现程序将抛出一个ConcurrentModificationException异常。

由异常能够发现抛出异常点正处于在调用next方法的checkForComodification方法出现了异常。这里也就出现上文描述的modCount != expectedModCount的状况,缘由是t2线程在读数据的时候,t1线程还在不断的添加元素。

这里modCount的做用也就显而易见了,用modCount来规避多线程中并发的问题。由此也能够看出ArrayList是非线程安全的类。

相关文章
相关标签/搜索