Java源码阅读——ArrayList

写在前面:自己学习Java源码的一些笔记,JDK版本为1.8.0_131

属性

    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     */
     // 默认的数组容量大小
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
     // 空数组,有参传入0,和传入的Collection大小为0,都使用这个空数组
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
     // 空数组,无参构造器使用的默认数组
    private static final Object[] DEFAULTCAPACITY_EMPTY_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修饰的属性在序列化时会被忽略。
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;
复制代码

构造器

1. ArrayList()

无参构造器,elementData指向了一个空的Object[]数组

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
复制代码

2. ArrayList(int initialCapacity)

有参构造器,传入参数为一个整数,为负数会抛出异常;输入为0,会指向一个空的Object[]数组,注意这个空数组跟无参构造器的空数组地址是不同的;输入大于0,会直接创建一个大小为输入参数的Object[]数组。

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    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);
        }
    }
复制代码

3. ArrayList(Collection<? extends E> c)

有参构造,传入参数为一个Collection对象。

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        // 将 Collection 对象通过 toArray() 转换成数组
        elementData = c.toArray();
        // 数组长度不为0并且toArray()没有返回Object数组,要将elementData转换为Object数组
        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 {
            //为零,直接指向EMPTY_ELEMENTDATA
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
复制代码

方法

1. add(E e)

该方法用于在ArrayList末尾添加指定元素,参数为添加的元素,返回值为boolean类型,表示是否添加成功。
add(E e)源码:

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        // 确认数组容量是否够用
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // 添加元素赋值到数组末尾,数组大小加一
        elementData[size++] = e;
        return true;
    }
复制代码

其中确认数组容量是否够用的方法为:

    // minCapacity 为数组所需的最小容量,对于add()操作来说,所需最小容量为 size + 1
    private void ensureCapacityInternal(int minCapacity) {
        // 数组是空数组,那么 minCapacity 从 size + 1(即1) 修改为默认值 10;
        // 非空数组,那么 minCapacity 修改为与 10 相比较的较大值
        // PS. 注意 if 语句中比较对象为 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
        // 通过有参构造构成出来的实例扩容时不会与默认值 10 比较
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        // 因为 add() 操作会导致数组结构性改变,因此 modCount 加一
        modCount++;

        // overflow-conscious code
        // minCapacity 与数组长度相比较,如果所需容量大于数组大小,实行扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
复制代码

扩容方法:

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // 新容量为旧容量的1.5倍(此运算可能会导致 int 溢出)
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        // 如果溢出了 将新容量再次改为需要的最小容量
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        // 如果需要的容量比系统设定的最大数组大小还大,调用hugeCapacity()
        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();
        // 需要的容量大于设定的数组最大长度,返回 Integer.MAX_VALUE ,否则返回 MAX_ARRAY_SIZE.
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
复制代码

add(E e)的具体实现中,主要是要观察现有的容量是否需要扩容,如果需要扩容,扩容规则为原容量的 1.5 倍。扩容的大小可能会超过允许的数组大小( int 溢出和需要容量大于设定的最大数组大小),当溢出的情况时,新数组大小为所需最小的容量;当大于设定最大容量时(MAX_ARRAY_SIZE),如果还是太大,超过Integer.MAX_VALUE,抛出异常,否则直接把数组大小变为Integer.MAX_VALUE大小。(MAX_ARRAY_SIZE比Integer.MAX_VALUE小8)。

2. add(int index, E element)

该方法用于在指定索引添加元素。参数 1 是要添加元素的索引,参数 2 是要添加的元素。
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++;
    }
复制代码

检查索引是否合法的方法为:

    /**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        // 索引小于 0 和 超过了数组的实际大小(不是容量!)均抛出异常
        // 在 ArrayList 源码中还有一个 rangeCheck() 方法。跟该方法略有不同。
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
复制代码

add(int index, E element)的具体实现中,相比add(E e)方法多了一步索引的合法性加成,并且在赋值之前,需要将指定索引及之后的元素都后一一位。实际上相当于插入元素,插入的位置必须大于等于0,小于等于数组的大小(等于数组大小相当于add(E e)),因此哪怕实际上数组的容量要大于输入的index,但只要不满足上述条件仍然会抛出异常。

3. addAll(Collection<? extends E> c)

该方法将传入的集合的元素加到ArrayList后面,返回值表明是否成功添加大于0个元素,添加0个元素返回false。

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
        // 将Collection转换为Object数组
        Object[] a = c.toArray();
        int numNew = a.length;
        // 添加操作,确认数组的容量
        ensureCapacityInternal(size + numNew);  // Increments modCount
        // 将a的所有元素复制到elementData的后面
        System.arraycopy(a, 0, elementData, size, numNew);
        // 更新size
        size += numNew;
        return numNew != 0;
    }
复制代码

4. addAll(int index, Collection<? extends E> c)

该方法将传入集合的元素添加到指定索引及之后处。

    /**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element from the
     *              specified collection
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        // 判断 index 是否小于0,是否大于数组目前长度
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        // 确认容量是否够用,不够扩容
        ensureCapacityInternal(size + numNew);  // Increments modCount

        int numMoved = size - index;
        // 先将原数组index索引及之后的元素后移
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        //将传入元素复制进数组
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }
复制代码

5. set(int index, E element)

该方法用于修改数组中已有元素的值,参数 1 时要修改元素的索引,参数 2 是修改后的值。方法会返回原来的值。set方法不会对ArrayList产生结构性的变化,因此不会导致modCount改变
set(int index, E element)源码:

    /**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        // 同样需要对索引进行合法性判断,但是跟add操作的具体要求不同
        rangeCheck(index);
        //保存原来的值,这里是一个叫 elementData 的方法
        E oldValue = elementData(index);
        // index处修改为新的值
        elementData[index] = element;
        return oldValue;
    }
复制代码

rangeCheck方法,这个方法在set、get和remove中都会用到:

    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        // 对于set、get和remove方法,索引等于数组大小,也是不对的。
        // 索引应当处于 0 到 size - 1之间。传入负数不会在抛出异常,但会在获取值的时候抛出异常(异常为ArrayIndexOutOfBoundsException)。
        // rangeCheckForAdd 会对输入负值进行判断,猜测是为了提高效率(?)
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
复制代码

6. get(int index)

该方法获取指定索引处的元素,参数为索引。

    /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        // 同样会对输入的索引进行检查
        rangeCheck(index);
        //返回指定索引处的元素
        return elementData(index);
    }
复制代码

7. remove(int index)

该方法移除指定索引处的元素。会返回移除的元素。

    /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        // 也会对 index 进行检查
        rangeCheck(index);
        
        // 移除也对数组进行了结构性改变, modCount 加一
        modCount++;
        // 记录被移除的元素
        E oldValue = elementData(index);

        // 移除一个元素后需要对移除索引后面的元素进行前移
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        // 末尾置为 null,size减一
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
复制代码

8. remove(Object o)

该方法为移除指定元素。返回值为boolean类型,表示的是是否成功移除元素

    /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    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++)
                // 对象需要使用 equals 来判断
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
复制代码

fastRemove源码为:

    /*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
        // 与remove(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
    }
复制代码

9. removeRange(int fromIndex, int toIndex)

该方法为移除指定索引范围内的元素。该方法被修饰为protected。具体范围为[fromIndex, toIndex),为一个左闭右开的区间。

    /**
     * Removes from this list all of the elements whose index is between
     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
     * Shifts any succeeding elements to the left (reduces their index).
     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
     * (If {@code toIndex==fromIndex}, this operation has no effect.)
     *
     * @throws IndexOutOfBoundsException if {@code fromIndex} or
     *         {@code toIndex} is out of range
     *         ({@code fromIndex < 0 ||
     *          fromIndex >= size() ||
     *          toIndex > size() ||
     *          toIndex < fromIndex})
     */
    protected void removeRange(int fromIndex, int toIndex) {
        // 即使一次移除多个元素,modCount也只加一次
        modCount++;
        // 需要移动的元素个数
        int numMoved = size - toIndex;
        // 仍然通过复制实现
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }
复制代码

10. removeAll(Collection<?> c) 和 retainAll(Collection<?> c)

removeAll()方法将ArrayList中存在的,所有Collection中的元素删除。例如 list1 中有 0 到 9 共 10 个元素, list2 有 2、4、6、8、10共 5 个元素,list1.removeAll(list2)会将 list1 中的 2、4、6、8给删除。
retainAll()方法则计算两个集合的交集。
把这两个方法放一起是因为它们源代码使用了同一个方法。
源码:

    /**
     * Removes from this list all of its elements that are contained in the
     * specified collection.
     *
     * @param c collection containing elements to be removed from this list
     * @return {@code true} if this list changed as a result of the call
     * @throws ClassCastException if the class of an element of this list
     *         is incompatible with the specified collection
     * (<a href="https://juejin.cn/post/Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if this list contains a null element and the
     *         specified collection does not permit null elements
     * (<a href="https://juejin.cn/post/Collection.html#optional-restrictions">optional</a>),
     *         or if the specified collection is null
     * @see Collection#contains(Object)
     */
    public boolean removeAll(Collection<?> c) {
        //非空检查
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }
    /**
     * Retains only the elements in this list that are contained in the
     * specified collection.  In other words, removes from this list all
     * of its elements that are not contained in the specified collection.
     *
     * @param c collection containing elements to be retained in this list
     * @return {@code true} if this list changed as a result of the call
     * @throws ClassCastException if the class of an element of this list
     *         is incompatible with the specified collection
     * (<a href="https://juejin.cn/post/Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if this list contains a null element and the
     *         specified collection does not permit null elements
     * (<a href="https://juejin.cn/post/Collection.html#optional-restrictions">optional</a>),
     *         or if the specified collection is null
     * @see Collection#contains(Object)
     */
    public boolean retainAll(Collection<?> c) {
        //非空检查
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }
复制代码

batchRemove(Collection<?> c, boolean complement)方法:

    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            // complement 为 true, elementData 记录集合交集
            // 为 false, elementData 记录 c 集合中没有的元素
            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.
            // 正常情况下 r == size, 出现不等说明执行 contains() 方法出现异常
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            // 如果complement为true, elementData存的是集合的交集
            // 此时如果w==size代表两个集合相同
            // 不同将把多余的元素置为null,modCount加上置为null元素的数量
            // 如果complement为false, elementData存的是做了集合减法后剩余的元素
            // w==size代表两个集合没有交集,因此未删除任何一个元素
            // 不同将多余的元素置为null,modCount加上置为null元素的数量
            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;
            }
        }
        // 返回值 modified 为 true,说明 elementData 产生了结构性变化(即执行置为null)
        // 1. ArrayList删除了元素
        // 2. ArrayList与传入集合有交集(交集长度小于size)
        // 3. ArrayList与传入集合没有交集(交集长度等于0)
        // 当为 false 时,几种可能情况:
        // 1. ArrayList未删除元素
        // 2. 传入集合有所有ArrayList集合元素的值(交集长度等于size)
        return modified;
    }
复制代码

removeAll()和retainAll()方法的核心方法为batchRemove()方法,batchRemove()方法根据传入参数complement来决定elementData保留什么元素,complement如果为true,保留交集的元素,如果为false,保留不应当被remove的元素。根据elementData的长度w来确认返回值。

11. clear()

该方法将ArrayList中的所有元素清空。

    /**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        // 同样属于结构性变化
        modCount++;

        // clear to let GC do its work
        // 将所有元素置为 null
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        // size变为 0
        size = 0;
    }
复制代码

12. indexOf(Object o)

该方法用于获取给定对象在ArrayList中第一次出现的索引位置,如果找不到指定对象,返回值为-1。

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    public int indexOf(Object o) {
        // 输入可能为 null,按索引顺序寻找是否有元素为 null
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            // 不为 null, 按索引顺序寻找是否有元素等于输入元素
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
复制代码

null要单独拿出来是因为虽然Object可以为null,但是调用equals()方法前会抛出空指针异常,不能使用equals()。

13. lastIndexOf(Object o)

获取给定对象在列表中最后一次出现的索引,如果没有查找到,返回-1。

    /**
     * Returns the index of the last occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the highest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    public int lastIndexOf(Object o) {
        // 跟indexOf的区别就是从后往前遍历
        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;
    }
复制代码

14. trimToSize()

该方法去掉预留的容量,只保留数组实际使用的长度需要的空间。

    /**
     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
     * list's current size.  An application can use this operation to minimize
     * the storage of an <tt>ArrayList</tt> instance.
     */
    public void trimToSize() {
        modCount++;
        // 仍然是通过数组的复制实现
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }
复制代码

15. clone()

该方法克隆ArrayList的实例,需要注意的是该方法为浅复制。

    /**
     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
     * elements themselves are not copied.)
     *
     * @return a clone of this <tt>ArrayList</tt> instance
     */
     //该方法返回的结果为Object对象
    public Object clone() {
        //复制原来的元素到新的ArrayList中
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }
复制代码

16. writeObeject(java.io.ObjectOutputStream s) 和 readObject(java.io.ObjectInputStream s)

因为elementData被关键字 transient 修饰,因此使用writeObject和readObject方法来进行序列化相关的操作。 (因为ArrayList的容量关系,序列化elementData会将很多null也给序列化,因此实际上序列化的时候只会序列化实际大小的数组)。

    /**
     * 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;
        //没有被tranisent修饰的会被序列化
        s.defaultWriteObject();

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

        // Write out all elements in the proper order.
        //将ArrayList中的元素依次序列化
        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();
            }
        }
    }
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享