youyichannel

志于道,据于德,依于仁,游于艺!

0%

带你阅读 ArrayList 源码

以下内容来自JDK8

ArrayList 简介

ArrayList的底层是数组队列,相当于动态数组(容量能够动态增长)。

接下来从ArrayList的继承链来看看其结构特点,ArrayList继承了AbstractList类,实现了ListRandomAccessCloneableSerializable接口。

public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
}
  1. 实现了List接口,表明它是一个列表,支持增删查改等操作,并且可以通过下标进行访问。
  2. 实现了RandomAccess接口,表明实现这个的List集合是支持快速随机访问的。即在ArrayList中,我们可以通过元素的需要快速获取元素对象,这就是快速随机访问。(RandomAccess是一个标志接口)
  3. 实现了Cloneable接口,表明它具有拷贝能力,可以进行浅拷贝和深拷贝。
  4. 实现了Serialzable接口,表明它可以进行序列化操作,也就是可以将对象转换为字节流进行持久化存储或者网络传输。

ArrayList可以添加null值吗?

ArrayList可以存储任何类型的对象,因为保存的容器是transient Object[] elementData;,这其中也包括null值。但是不建议这么干,因为null值没有任何意义,会让代码难以维护,提高出现NPE的风险。

ArrayList#add(E)

public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
// ArrayList添加元素的实质就相当于为数组赋值
elementData[size++] = e;
return true;
}

ArrayList核心源码

不包含扩容机制的代码,这个我们后续单独分析

构造方法

/**
* 默认的初始容量为10
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;

/**
* 用于空实例的空数组
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};

/**
* 用于默认大小空实例的共享空数组示例。和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 = {};

/**
* 保存ArrayList数据的数组
*
* 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

/**
* ArrayList中所包含的元素个数
* The size of the ArrayList (the number of elements it contains).
*
* @serial 是一个标签,用于记录序列化版本号的相关信息。
*/
private int size;

/**
* 带初始容量参数的构造函数
* 用户可以在创建ArrayList对象时指定集合的初始大小
* Constructs an empty list with the specified initial capacity.
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
// 如果传入的参数大于0,创建initialCapacity大小的数组
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
// 如果传入的参数为0,创建空数组
this.elementData = EMPTY_ELEMENTDATA;
} else {
// 其他情况,抛出异常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}

/**
* 默认无参构造函数
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
// DEFAULTCAPACITY_EMPTY_ELEMENTDATA为空数组,初始化为10 => 初始是空数组,当添加第一个元素时
// 数组容量变为10
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

/**
* 构造一个包含指定集合的元素的列表(按照由集合迭代器返回的顺序)
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*/
public ArrayList(Collection<? extends E> c) {
// 将指定的集合转化为数组
Object[] a = c.toArray();
// 如何数组的长度不为0
if ((size = a.length) != 0) {
// 如果a数组的类型是ArryList类型,直接赋值给elementData
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
// 不是ArrayList类型,将原来不是ArrayList类型的数组内容赋值给新的Object类型的elementData数组
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// 其他情况,使用空数组代替
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}

容器大小类

/**
* 修改当前ArrayList实例的容量为列表的大小
* 应用程序可以使用此操作最小化ArrayList实例的存储
*
* 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);
}
}
/**
* 返回列表中的元素数
* Returns the number of elements in this list.
*/
public int size() {
return size;
}

/**
* 如果此列表中不包含元素返回true
* Returns <tt>true</tt> if this list contains no elements.
*/
public boolean isEmpty() {
return size == 0;
}

判断元素类

/**
* 如果列表中包含了指定的元素o,返回true
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}

/**
* 返回列表中指定元素首次出现的索引,如果不包含指定元素,返回-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.
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
// 使用equals()方法比较
if (o.equals(elementData[i]))
return i;
}
return -1;
}

/**
* 返回列表中指定元素最后一次出现的索引,如果不包含指定元素,返回-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.
*/
public int lastIndexOf(Object o) {
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;
}

拷贝相关

/**
* 返回此ArrayList实例的浅拷贝(元素本身不被复制)
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
// Arrays.copyOf()方法是实现数组的复制,返回复制后的数组,参数是被复制的数组和复制的长度
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);
}
}

转换数组

/**
* 以一定的顺序(从第一个元素到最后一个元素)返回一个包含此列表中所有元素的数组
* 返回的数组是“安全的”,因为该列表不保留对它的引用(即这个方法分配了一个新的数组)。
* 因此调用者可以自由地修改返回的数组,此方法饰演阵列和基于集合的API之间的桥梁角色。
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}

/**
* 以一定的顺序(从第一个元素到最后一个元素)返回一个包含此列表中所有元素的数组
* 返回的数组的运行时类型是指定数组的运行时类型。如果列表适合指定的数组,则返回该列表,
* 否则,将为指定的数组的运行时类型和此列表的大小分配一个新数组。
* 如果列表适合指定的数组,其余空间(即数组的元素数量多余此列表元素数量),则紧跟在集合结束后的
* 数组中元素设置为null。
* Returns an array containing all of the elements in this list in proper
* sequence (from first to last element); the runtime type of the returned
* array is that of the specified array. If the list fits in the
* specified array, it is returned therein. Otherwise, a new array is
* allocated with the runtime type of the specified array and the size of
* this list.
*
* <p>If the list fits in the specified array with room to spare
* (i.e., the array has more elements than the list), the element in
* the array immediately following the end of the collection is set to
* <tt>null</tt>. (This is useful in determining the length of the
* list <i>only</i> if the caller knows that the list does not contain
* any null elements.)
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// 新建一个运行时类型的数组,但是ArrayList数组的内容
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}

范围检查类

/**
* 检查给定的索引是否在合法范围内
* 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) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

/**
* 检查添加元素的索引范围是否合法
* A version of rangeCheck used by add and addAll.
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}

元素操作类

/**
* 返回此列表中指定位置的元素
* Returns the element at the specified position in this list.
*/
public E get(int index) {
rangeCheck(index);

return elementData(index);
}

/**
* 用指定的元素替换此列表中指定位置的元素
* Replaces the element at the specified position in this list with
* the specified element.
*/
public E set(int index, E element) {
rangeCheck(index);

E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}

/**
* 将指定的元素追加到列表的末尾
* Appends the specified element to the end of this list.
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}

/**
* 在此列表中的指定元素插入指定的元素
*
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*/
public void add(int index, E element) {
rangeCheckForAdd(index); // 范围检查

ensureCapacityInternal(size + 1); // Increments modCount!!
// 将从index开始之后的所有成员后移一个位置
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}

/**
* 删除该列表中指定位置的元素
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*/
public E remove(int index) {
rangeCheck(index);

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

int numMoved = size - index - 1;
if (numMoved > 0)
// 将index + 1开始之后的元素左移一个位置
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work

return oldValue; // 返回从列表中删除的元素
}

/**
* 从列表中删除指定元素(第一个出现在列表中的),如果不包含该元素,不会更改。
* 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).
*/
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;
}

/**
* 清空列表元素
* 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
for (int i = 0; i < size; i++)
elementData[i] = null;

size = 0;
}

/**
* 按指定集合的Iterator返回的顺序将指定集合中的所有元素追加到此列表的末尾。
* 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.)
*/
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;
return numNew != 0;
}

/**
* 将指定集合中的所有元素插入到此列表中,从指定的位置开始。
* 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.
*/
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;
}

/**
* 从此列表中删除所有索引为 [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.)
*/
protected void removeRange(int fromIndex, int toIndex) {
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;
}
/**
* 此列表中删除指定集合中包含的所有元素。
* Removes from this list all of its elements that are contained in the
* specified collection.
*/
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.
*/
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}

迭代器相关

/**
* 从列表中返回从指定位置开始的按照正确顺序的列表迭代器
* Returns a list iterator over the elements in this list (in proper
* sequence), starting at the specified position in the list.
* The specified index indicates the first element that would be
* returned by an initial call to {@link ListIterator#next next}.
* An initial call to {@link ListIterator#previous previous} would
* return the element with the specified index minus one.
*/
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}

/**
* 返回列表中的列表迭代器(按适当的顺序)。
* 返回的列表迭代器是fail-fast 。
* Returns a list iterator over the elements in this list (in proper
* sequence).
*
* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*/
public ListIterator<E> listIterator() {
return new ListItr(0);
}

/**
* 以正确的顺序返回该列表中的元素的迭代器。
* 返回的迭代器是fail-fast 。
* Returns an iterator over the elements in this list in proper sequence.
*
* <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*/
public Iterator<E> iterator() {
return new Itr();
}

ArrayList的扩容机制

先从构造器开始

private static final Object[] EMPTY_ELEMENTDATA = {};

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

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

public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

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

以无参构造器创建ArrayList时,实际上初始化赋值的是一个空数组。当真正对数组进行添加元素操作时,才真正分配容量,即向数组中添加第一个元素时,数组容量扩充为10.

一步一步分析

以无参构造器创建的ArrayList为例

add方法

public boolean add(E e) {
// 加入元素前,先调用了ensureCapacityInternal方法保证列表的容量
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}

ensureCapacityInternal方法:

private static final int DEFAULT_CAPACITY = 10;

// 确保内部容量达到指定的最小容量
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

// 根据给定的最小容量和当前数组元素来计算所需容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
// 如果当前数组为空数组(初始情况),返回默认容量和最小容量中的较大值作为所需要容量
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
// 否则直接返回最小容量
return minCapacity;
}

ensureExplicitCapacity方法:

// 判断当前是否需要扩容
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 判断当前数组容量是否足以存储minCapacity个元素
// overflow-conscious code
if (minCapacity - elementData.length > 0)
// 不足则调用grow方法进行扩容
grow(minCapacity);
}

我们来梳理一下流程:

  • 使用无参构造器创建ArrayList实例对象
  • 当我们要add第一个元素时,elementData.length == 0,因为执行了calculateCapacity方法,所以传递给ensureExplicitCapacity方法的参数是10(DEFAULT_CAPACITY),之后进入到grow()方法中进行扩容

grow方法

// 要分配的最大数组大小
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// newCapacity = oldCapacity * 1.5 => 扩容为旧容量的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 检查新容量是否满足最小需要容量,如果不满足,那么就把最小需要容量当做数组的新容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// 如果新容量大于MAX_ARRAY_SIZE,执行hugeCapacity方法,比较minCapacity和MAX_ARRAY_SIZE
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();
// 如果minCapacity大于最大容量,则新容量为Integer.MAX_VALUE,否则为MAX_ARRAY_SIZE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}

int newCapacity = oldCapacity + (oldCapacity >> 1),所以 ArrayList 每次扩容之后容量都会变为原来的 1.5 倍左右(oldCapacity 为偶数就是 1.5 倍,否则是 1.5 倍左右)! 奇偶不同。

接着上面的分析:

  • 第一次添加元素进入到grow()方法扩容后,oldCapacity = 0, newCapacity = 10,所以数组的容量为10
  • add第十一个元素时,又要进入到grow()方法了,此时newCapacity = 15minCapacity = 11,此时也不会执行hugeCapacity方法,因此数组扩容为15
  • 以此类推...

System.arrayCopy() VS Arrays.copy()

经历了上面的源码阅读,我们发现ArrayList中大量使用到了这两个方法。

System.arrayCopy()

可以看到这是一个native方法。

/**
* 复制数组
*
* @param src 源数组
* @param srcPos 源数组中的起始位置
* @param dest 目标数组
* @param destPos 目标数组中的起始位置
* @param length 要复制的数组元素的数量
*/
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);

Arrays.copyOf()

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
// 调用System.arraycopy(),将源数组中的数据进行拷贝,并返回新的数组
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}

二者区别和联系

联系

Arrays.copyOf()内部实际上调用了System.arrayCopy()方法

区别

  • System.arrayCopy()需要目标数组,将原数组拷贝到自己定义的数组里或者原数组,而且可以选择拷贝的起点和长度以及放入新数组中的起始位置
  • Arrays.copyOf()是在系统内部新建一个数组,并返回该数组

ArrayList 中的 elementData 为什么被 transient 修饰?

transient Object[] elementData; // non-private to simplify nested class access

在 Java 中,被 transient 修饰的对象默认不会被序列化。

那么在序列化后,ArrayList 里面的元素数组保存的数据不就完全丢失了吗?

其实并不会,ArrayList 提供了两个用于序列化和反序列化的方法, readObjectwriteObject。ArrayList 在序列化的时候会调用 writeObject,将 size 和 element 写入ObjectOutputStream; 反序列化时调用 readObject,从 ObjectInputStream 获取 size 和 element ,再恢复到 elementData

@java.io.Serial
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 behavioral 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();
}
}

@java.io.Serial
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {

// Read in size, and any hidden stuff
s.defaultReadObject();

// Read in capacity
s.readInt(); // ignored

if (size > 0) {
// like clone(), allocate array based upon size not capacity
SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);
Object[] elements = new Object[size];

// Read in all elements in the proper order.
for (int i = 0; i < size; i++) {
elements[i] = s.readObject();
}

elementData = elements;
} else if (size == 0) {
elementData = EMPTY_ELEMENTDATA;
} else {
throw new java.io.InvalidObjectException("Invalid size: " + size);
}
}

ArrayList 为什么不直接用 elementData 来序列化,而采用上面的方式来实现序列化呢?

原因在于 elementData 是一个缓存数组,默认 capacity=10,对 ArrayList 进行添加操作,当空间不足时, 会对 ArrayList 进行扩容,通常扩容的倍数为1.5倍。因此 elementData 数组会预留一些容量,等容量不足时再扩充容量,那么有些空间可能就没有实际存储元素,采用上面的方式来实现序列化时,就可以保证只序列化实际存储的那些元素,而不是整个数组,从而节省空间和时间