ArrayList源码分析基础
1.先看ArrayList的图:

相关的接口抽象类的介绍:
| 类名 | 说明 |
| AbstractCollection |
实现了Collection中大量的函数,除了特定的几个函数iterator()和size()之外的函数 |
| AbstractList |
该接口继承于AbstractCollection,并且实现List接口的抽象类。 它实现了List中除size()、get(int location)之外的函数。 AbstractList的主要作用:它实现了List接口中的大部分函数和AbstractCollection相比,AbstractList抽象类中,实现了iterator()接口 |
| RandomAccess |
RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在ArrayList中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问 |
| List |
有序队列接口,提供了一些通过下标访问元素的函数 List是有序的队列,List中的每一个元素都有一个索引;第一个元素的索引值是0,往后的元素的索引值依次+1 |
ArrayList本质是动态数组。那么ArrayList是如何实现动态扩容的呢?
ArrayList的长度
/** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;
ArrayList中存储数据的数组对象
/** * Default initial capacity. 默认初始大小 */ private static final int DEFAULT_CAPACITY = 10; /** * Shared empty array instance used for empty instances. 一个空对象 */ 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 Object[] elementData; // non-private to simplify nested class access
无参构造器
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
elementData=null;无参构造去并不会真实的创建数组,数组会在add方法中去创建,有助于性能的提升,懒加载的方式。
有参构造器
/** * 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); } }
add方法分析
/** * 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) {
// 确定容量,动态扩容 size 初始为0 ensureCapacityInternal(size + 1); // Increments modCount!!
// 数组扩容后将数据添加到合适的位置 并size+1
elementData[size++] = e; return true; }
接下来看:ensureCapacityInternal
private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); }
接着看:calculateCapacity
private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { // 如果使用无参构造函数 第一次为true,返回10 return Math.max(DEFAULT_CAPACITY, minCapacity); // 比较默认值和 minCapacity中的一个大的值 } return minCapacity; }
接下来看: ensureExplicitCapacity
private void ensureExplicitCapacity(int minCapacity) {
modCount++; //操作次数
// overflow-conscious code
if (minCapacity - elementData.length > 0) //判断是否需要扩容 第一次add的时候触发扩容,minCapacity为10
grow(minCapacity);
}
接下来看:grow
/** * 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; // 获取旧数组的长度 int newCapacity = oldCapacity + (oldCapacity >> 1); // 将旧数字变为原来的1.5倍(因为左移动1位) 第一次 0 还是变成0 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; // 第一次add的时候 newCapacity 变为10(无参构造函数) 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); //把原来数组中的内容拷贝到一个新建的指定容量为newCapacity的数组中,扩容 }
尝试基本的逻辑:
使用无参构造函数
第1次add的时候,触发扩容,容量为10。当前数组为:{0,,,,,,,,,}。当前size 1
第2次add的时候,不触发扩容,容量为10。当前数组:{0,1,,,,,,,,,} 当前size 2
第11次add的时候,触发扩容,容量为15,当前数组为:{0,1,2,3,4,5,6,7,8,9,10,,,,} 当前size 11
执行: // ensureExplicitCapacity(11) private void ensureExplicitCapacity(int minCapacity) { modCount++; // 11 - 10 > 0 if (minCapacity - elementData.length > 0) grow(minCapacity); } private void grow(int minCapacity) { // 11 // 10 int oldCapacity = elementData.length; // 15 newCapacity 是oldCapacity的1.5倍 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: // {0,1,2,3,4,5,6,7,8,9} -- > {0,1,2,3,4,5,6,7,8,9,,,,,} elementData = Arrays.copyOf(elementData, newCapacity); }
最终变成:{0,1,2,3,4,5,6,7,8,9,10,,,,}
get方法
/** * 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); } @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; }
set方法
/** * 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) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
remove方法
/** * 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 = 3 rangeCheck(index); 检查下标 modCount++;
// 获取要移动的元素的个数 {0,1,2,3,4,5,6,7,8} // 3 size=9 index=3(下标为3) E oldValue = elementData(index); // oldValue = 3 int numMoved = size - index - 1; // 获取要移动元素的个数 9 - 3 -1 = 5 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); // 源数组 开始下标 目标数组 开始下标 长度
// 当前数组:{0,1,2,4,5,6,7,8,,} elementData[--size] = null; // clear to let GC do its work return oldValue; }
FailFast机制
@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];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
快速失败的机制,Java集合类为了应对并发访问在集合迭代过程中,内部结构发生变化的一种防护措施,这种错误检查的机制为这种可能发生错误通过抛出 java.util.ConcurrentModificationException
浙公网安备 33010602011771号