阅读ArrayList源码,学习到以下:
1.ArrayList是动态数组,底层是数组,有以下核心成员变量
a.存储元素的数组
transient Object[] elementData;
b.记录元素的个数
private int size;
c.初始容量
private static final int DEFAULT_CAPACITY = 10;
d.默认空数组,为了首次添加元素时候判断需要扩容多少用
/** * 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 = {};
e.结构更改次数,add,remove,扩容等结构性修改的时候,modCount会+1,主要为了fail-fast
protected transient int modCount = 0;
f.最大容量,由于一些vm需要保留一些空间作为数组头,所以需要留一些空间
/** * The maximum size of array to allocate. * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
2.ArrayList支持序列化,但elementData却为transient
因为elementData的长度可能超过size的长度,如果把elementData全部序列化,会拷贝很多空值,序列化时候,重写writeObject方法
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(); } }