ArrayList源码分析

作者: 一个不熬夜的孩子 | 来源:发表于2016-12-30 00:18 被阅读98次

ArrayList 源码分析

@(Java)

前几天看了一下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);
    }
}

/**
 * 默认的数组大小为10
 */
public ArrayList() {
    // 在构造函数中,只是指向了一个空的数组,并没有new 出10个空间的数据,
    // 10个空间的数据是在add()调用的时候才new的
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA;
    }
}

构造器的源码很简单,很好理解。

接着向下看,我们最常用的就是add()方法了:

public boolean add(E e) {
    // 判断是否需要扩容
    ensureCapacityInternal(size + 1);
    elementData[size++] = e;
    return true;
}
private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // 扩容
    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);
}
private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

add()方法的逻辑也很好理解,就是判断添加的数据量有没有达到数组的容量,如果达到了就扩容。然后将就之前的数据全部拷贝过去。

ArrayList的其他源码的思路很好理解,这里就不一一列出来了。就是我们平常的查找、删除的算法的封装。这里说说我在看一下源码的时候发现的问题:

transient关键字

我们看看用来保存数据的elementData的定义:

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer. Any
 * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 * will be expanded to DEFAULT_CAPACITY when the first element is added.
 */
transient Object[] elementData; // non-private to simplify nested class access

我们看到它是被transient修饰的,那么transient关键字是什么东西呢。简单来说,就是在序列化的过程中不序列化被transient修饰的成员变量。那么问题来了,刚刚我们说了elementData是用来保存ArrayList的数据的,那么他被transient修饰了,所以他在序列化的时候不会被序列化进去,那我的数据呢?跑哪里去了?我们在看看ArrayList里面的两个方法:

 /**
* Save the state of the <tt>ArrayList</tt> instance to a stream (that
 * is, serialize it).
 *
 * @serialData The length of the array backing the <tt>ArrayList</tt>
 *             instance is emitted (int), followed by all of its elements
 *             (each an <tt>Object</tt>) in the proper order.
 */
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();
    }
}

/**
 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
 * deserialize it).
 */
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();
        }
    }
}

在回想一下我们的ArrayList是实现了Serializable接口的,在Serializable文档中有说明,如果需要特殊处理,可以实现writeObject和readObject方法。所以上面的两个方法是用来处理ArrayList的序列化的。那么又有问题了,为什么要那么麻烦使用一个transient修饰elementData和额外实现两个方法呢。我们别忘了,我们的elementData并不是所有的空间都被使用的,还有一部分的空间是多余的。如果我们直接序列化,我们会被这部分的空间也序列化进去,我们关系的是我们的数据,所以谢了一个writeObject把我们的数据序列化进入而不是把整个数组序列化进去。

以前特别的畏惧看源码,觉得源码很难,其实源码有很多值得我们学习的地方。

相关文章

网友评论

    本文标题:ArrayList源码分析

    本文链接:https://www.haomeiwen.com/subject/zrapvttx.html