源码分析之ArrayList

源码分析之ArrayList 


概念


ArrayList是我们常用的集合类,是基于数组实现的。不同于数组的是ArrayList可以动态扩容。

类结构 ArrayList是Java集合框架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在序列化和反序列化的过程中,有两个值得关注的方法:writeObject和 readObject:

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中的size和element数据写入ObjectOutputStream。readObject会从ObjectInputStream读取size和element数据。

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

size private int size; size是ArrayList的大小。

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方法中可以看出,ArrayList的elementData数组如遇到容量不足时,将会把新容量newCapacity设置为 oldCapacity + (oldCapacity >> 1)。二进制位操作>> 1等同于/2的效果,扩容导致的newCapacity也就设置为原先的1.5倍。

如果新的容量大于MAXARRAYSIZE。将会调用hugeCapacity将int的最大值赋给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++;
}

带有index的add方法相对于直接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 在add、remove过程中,经常发现会有modCount++或者modCount--操作。这里来看下modCount是个啥玩意。

modCount变量是在AbstractList中定义的。

protected transient int modCount = 0;

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

modCount起作用的地方是在使用iterator的时候。ArrayList的iterator方法。

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的作用。简单介绍一下这个小例子:准备两个线程t1、t2,两个线程对同一个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是非线程安全的类。

https://juejin.im/post/58edf7cbb123db43cc36f47f


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值