源码几个关键的点
ArrayList使用无参构建函数创建是创建了一个空数组,名字是DEFAULTCAPACITY_EMPTY_ELEMENTDATA,然后第一次使用add()添加的时候才会进行扩容,这是懒加载方式
使用有参构造函数创建,如果参数是0就创建一个空数组,名字是EMPTY_ELEMENTDATA,如果参数大于0,就用这个参数创建一个数组
add()方法流程:
先看需不需要扩容:minCapacity加1,如果当前数组是空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA,就用默认容量和+1后的minCapacity比较,取最大值为minCapacity,否则不用比较,然后判断是否比当前数组的长度大,是的话就调用grow方法进行扩容
grow方法:
先取当前数组长度,新数组长度为当前数组长度1.5倍,然后判断新数组长度是否小于minCapacity,小于的话就用minCapacity作为新数组长度,如果新数组长度大于数组长度的上限,再判断minCapacity是否大于数组长度的上限,是的话就把MAX_VALUE作为新数组长度,否的话把数组长度的上限作为新数组长度,最后调用Arrays.copyOf()方法把旧数组的值移到扩容后的数组
流程图如下
源码里很多地方都用到了Array.copyOf()这个方法,例如删除和添加元素
整个ArrayList源码文件
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity. 默认初始容量大小
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances. 一个空数组,当用户指定ArrayList容量为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 = {
};
/**
* 一个空数组实例
* - 当用户没有指定 ArrayList 的容量时(即调用无参构造函数),返回的是该数组==>刚创建一个 ArrayList 时,其内数据量为 0。
* - 当用户第一次添加元素时,该数组将会扩容,变成默认容量为 10(DEFAULT_CAPACITY) 的一个数组===>通过 ensureCapacityInternal() 实现
* 它与 EMPTY_ELEMENTDATA 的区别就是:该数组是默认返回的,而后者是在用户指定容量为 0 时返回
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
* ArrayList 所包含的元素个数
* @serial
*/
private int size; //size是数组个数 elementData.length是数组容量
/**
* Constructs an empty list with the specified initial capacity.
* 带初始容量参数的构造函数(用户可以在创建ArrayList对象时自己指定集合的初始大小)
* @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]; //如果传入的参数大于0,创建initialCapacity大小的数组
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA; //如果传入的参数等于0,创建空数组
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity); //其他情况,抛出异常
}
}
/**
* Constructs an empty list with an initial capacity of ten. 默认无参构造函数
*/
public ArrayList() {
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.
* 创建一个包含collection的ArrayList
* @param c 要放入 ArrayList 中的集合,其内元素将会全部添加到新建的 ArrayList 实例中
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
Object[] a = c.toArray(); //将指定集合转换为Object数组
if ((size = a.length) != 0) {
//如果elementData数组的长度不为0
if (c.getClass() == ArrayList.class) {
// 如果指定集合是ArrayList就直接赋值给elementData数组
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);//将原来不是Object类型的elementData数组的内容,赋值给新的Object类型的elementData数组
}
} else {
// replace with empty array. // 其他情况,用空数组代替
elementData = EMPTY_ELEMENTDATA;
}
}
/**
* 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. 修改这个ArrayList实例的容量是列表的当前大小。 应用程序可以使用此操作来最小化ArrayList实例的存储。
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
/** 指定 ArrayList 的容量
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument. 如有必要,增加此ArrayList实例的容量,以确保它至少能容纳元素的数量
*
* @param minCapacity the desired minimum capacity 所需的最小容量
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0 //判断是不是空的ArrayList,如果是的最小扩充容量10,否则最小扩充量为0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
// 若用户指定的最小容量 > 最小扩充容量,则以用户指定的为准,否则还是 10
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
// 若 elementData == {},则取 minCapacity 为 默认容量和参数 minCapacity 之间的最大值 默认容量是10
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity); // 获取“默认的容量”和“传入参数”两者之间的最大值
}
return minCapacity;
}
//得到最小扩容量
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
//判断是否需要扩容
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code // 防止溢出代码:确保指定的最小容量 > 数组缓冲区当前的长度
if (minCapacity - elementData.length > 0) //指定的最小容量比当前数组大就扩容
grow(minCapacity);//调用grow方法进行扩容,调用此方法代表已经开始扩容了
}
/**
* 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 要分配的最大数组大小,-8是有8位是用来标记数组长度的
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/** 扩容,以确保 ArrayList 至少能存储 minCapacity 个元素
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
* ArrayList扩容的核心方法
* @param minCapacity the desired minimum capacity 指定的最小容量
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length; // oldCapacity为旧容量,newCapacity为新容量
int newCapacity = oldCapacity + (oldCapacity >> 1); //newCapacity为oldCapacity的1.5倍 >>1是右移一位除以2
if (newCapacity - minCapacity < 0) //然后检查新容量是否小于最小需要容量,若还是小于最小需要容量,那么就把最小需要容量当作数组的新容量,例如数组为空的时候新容量为5 最小容量为10 这时新容量为10
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0) //再检查新容量是否超出了ArrayList所定义的最大容量
newCapacity = hugeCapacity(minCapacity);//若超出了,则调用hugeCapacity()来比较minCapacity和 MAX_ARRAY_SIZE
// minCapacity is usually close to size, so this is a win://如果minCapacity大于MAX_ARRAY_SIZE,则新容量则为Interger.MAX_VALUE,否则,新容量大小则为 MAX_ARRAY_SIZE。
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;
}
/**
* Returns the number of elements in this list.
* 返回此列表中的元素数
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* Returns <tt>true</tt> if this list contains no elements.
* 如果此列表不包含元素,则返回 true
* @return <tt>true</tt> if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 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
* <tt>(o==null ? e==null : o.equals(e))</tt>.
* 如果此列表包含指定的元素,则返回true
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) >= 0; //indexOf()方法:返回此列表中指定元素的首次出现的索引,如果此列表不包含此元素,则为-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 ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)//指定元素为null就找第一个null的
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -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 ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
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;
}
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
* 返回此ArrayList实例的浅拷贝。 (元素本身不被复制。)
* @return a clone of this <tt>ArrayList</tt> instance
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);//Arrays.copyOf功能是实现数组的复制,返回复制后的数组。参数是被复制的数组和复制的长度
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable // 这不应该发生,因为我们是可以克隆的
throw new InternalError(e);
}
}
/**
* 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.
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
* 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.)
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size) // 若数组a的大小 < ArrayList的元素个数,则新建一个T[]数组
// 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);// 若数组a的大小 >= ArrayList的元素个数,则将ArrayList的全部元素都拷贝到数组a中。
if (a.length > size)
a[size] = null;
return a;
}
// Positional Access Operations
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[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);
}
/**
* 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;
}
/**
* Appends the specified element to the end of this list.
* 增加指定的元素到ArrayList的最后位置
* @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); // 元素个数加1
elementData[size++] = e; //保证要存多少个元素,就只分配多少空间资源 这里看到ArrayList添加元素的实质就相当于为数组赋值 先赋值 size再加1
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). 用于内部优化,保证空间资源不被浪费:尤其在 add() 方法添加时起效
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
rangeCheckForAdd(index);
//第二个是从要复制的数组的第几个开始,第四个是复制到的数组第几个开始,最后一个是复制长度
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);//从index开始的元素都右移一位(包括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).
* index 之后的所有元素依次左移一位(不包括index)
* @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) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);//要移除的值
int numMoved = size - index - 1;//要移动的长度 -1是因为不包括index
if (numMoved > 0)
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 ? get(i)==null : 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).
* 移除list中指定的第一个元素(符合条件索引最低的) 如果包含这个元素,index 之后的所有元素依次左移一位
* @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++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed. 快速删除第 index 个元素,和public E remove(int index)相比会跳过边界检查,不会返回被删除的元素
*/
private void fastRemove(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
}
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.移除list中的所有元素,这个list表将在调用之后置空,它会将数组缓冲区所以元素置为 null,list会变为{}
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
/**
* 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.)
* 将一个集合的所有元素顺序添加(追加)到 list 末尾,不过不是线程安全的
* @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) {
Object[] a = c.toArray();
int numNew = a.length;//要添加元素的个数
ensureCapacityInternal(size + numNew); // Increments modCount,看要不要扩容
System.arraycopy(a, 0, elementData, size, numNew);//把集合c复制到list里
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.
* 从 List 中指定位置开始插入指定集合的所有元素,
* @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) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;//要添加集合的元素数量
ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index;//原来list中要移动的数量
if (numMoved > 0)//从index开始后面的元素右移 0 1 4 5 6 从4添加 2 3,4 5 6右移两位 变成 0 1 _ _ 4 5 6
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
//把指定集合的元素复制到list
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
/**
* 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.)
* 移除list中 [fromIndex,toIndex) 的元素
* @throws IndexOutOfBoundsException if {@code fromIndex} or
* {@code toIndex} is out of range
* ({@code fromIndex < 0 ||
* fromIndex >= size() ||
* toIndex > size() || 从toIndex之后(包括toIndex)的元素向前移动(toIndex-fromIndex)个元素
* toIndex < fromIndex}) remove的元素不包括toIndex,左闭右开
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex; //要移动的数量 0 1 2 3 4 from是1 to是3 numMoved = 5 - 3 = 2 3左移2位 变成0 3 4 3 4
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; // 把后面元素置空 0 3 4 3 4 变成 0 3 4
}
size = newSize;
}
/** 越界检查
* 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;
}
/**
* Removes from this list all of its elements that are contained in the
* specified collection.
* 移除list中指定集合包含的所有元素
* @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 如果list中的一个元素的类和指定集合不兼容 类型不同
* (<a href="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="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null 如果list中包含一个空元素,而指定集合中不允许有空元素
* @see Collection#contains(Object)
*/
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);//判断集合是否为空,如果为空报NullPointerException
return batchRemove(c, false);//批量移除c集合的元素,第二个参数:是否采补集
}
/**
* 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="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="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);
}
//批量移除 @param c 要移除的集合 @param complement 是否是补集 true 移除list中除c中的所有元素 false 移除list中c的元素
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++) //补集的话就移除c以外的元素,保留c
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
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;
}
}
return modified;
}
/**
* Save the state of the <tt>ArrayList</tt> instance to a stream (that
* is, serialize it).
* 将ArrayList实例序列化 把ArrayList实例写入输出流
* @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);//写入clone行为的容量大小
// 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). 从输入流读出ArrayList实例
*/
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 // 从输入流中读取ArrayList的size
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
int capacity = calculateCapacity(elementData, size);
SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, 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();
}
}
}
/**
* 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.
* 返回从指定索引开始到结束的带有元素的list迭代器
* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
/**
* 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>.
*
* @see #listIterator(int)
*/
public ListIterator<E> listIterator() {
return new ListItr(0);
}
/**
* 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>.
*
* @return an iterator over the elements in this list in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr Itr是AbstractList.Itr的优化版本
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return // 下一个元素返回的索引
int lastRet = -1; // index of last element returned; -1 if no such // 最后一个元素返回的索引 -1 if no such
int expectedModCount = modCount;
Itr() {
} //Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,
// 这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,然后抛出ConcurrentModificationException 异常
public boolean hasNext() {
//所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象,
return cursor != size; //Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;//i当前元素的索引
if (i >= size)//第一次检查:索引是否越界
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)//第二次检查,list集合中数量是否发生变化
throw new ConcurrentModificationException();
cursor = i + 1; //cursor 下一个元素的索引
return (E) elementData[lastRet = i]; //返回当前元素
}
//移除集合中的元素
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);//移除list中的元素
cursor = lastRet; //由于cursor比lastRet大1,所有这行代码是指指针往左移动一位
lastRet = -1;//将最后一个元素返回的索引重置为-1
expectedModCount = modCount;//重新设置了expectedModCount的值,避免了ConcurrentModificationException的产生
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//将list中的所有元素都给了consumer,可以使用这个方法来取出元素
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
//检查modCount是否等于expectedModCount 在迭代时list集合的元素数量发生变化时会造成这两个值不相等
final void checkForComodification() {
if (modCount != expectedModCount) //当expectedModCount和modCount不相等时,就抛出ConcurrentModificationException
throw new ConcurrentModificationException();
}
}
/**
* An optimized version of AbstractList.ListItr AbstractList.ListItr 的优化版本
*/ //和普通的 Iterator 的区别,可以双向移动,可以添加元素
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
//是否有前一个元素
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
//获取 cursor 前一个元素的索引
public int previousIndex() {
//是 cursor 前一个,而不是当前元素前一个的索引。
return cursor - 1; //若调用 next() 后马上调用该方法,则返回的是当前元素的索引。
} //若调用 next() 后想获取当前元素前一个元素的索引,需要连续调用两次该方法。
//返回 cursor 前一元素
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0) //第一次检查:索引是否越界
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) //第二次检查
throw new ConcurrentModificationException();
cursor = i; //cursor左移
return (E) elementData[lastRet = i];//返回 cursor 前一元素
}
//将数组的最后一个元素,设置成元素e 更新
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//添加元素 新增
public void add(E e) {
checkForComodification();
try {
int i = cursor;//取出当前元素的索引
ArrayList.this.add(i, e); //在i位置上添加元素e
cursor = i + 1;//cursor后移一位
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
/**
* Returns a view of the portion of this list between the specified
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
* {@code fromIndex} and {@code toIndex} are equal, the returned list is
* empty.) The returned list is backed by this list, so non-structural
* changes in the returned list are reflected in this list, and vice-versa.
* The returned list supports all of the optional list operations.
*
* <p>This method eliminates the need for explicit range operations (of
* the sort that commonly exist for arrays). Any operation that expects
* a list can be used as a range operation by passing a subList view
* instead of a whole list. For example, the following idiom
* removes a range of elements from a list:
* <pre>
* list.subList(from, to).clear();
* </pre>
* Similar idioms may be constructed for {@link #indexOf(Object)} and
* {@link #lastIndexOf(Object)}, and all of the algorithms in the
* {@link Collections} class can be applied to a subList.
*
* <p>The semantics of the list returned by this method become undefined if
* the backing list (i.e., this list) is <i>structurally modified</i> in
* any way other than via the returned list. (Structural modifications are
* those that change the size of this list, or otherwise perturb it in such
* a fashion that iterations in progress may yield incorrect results.)
* 获取从 fromIndex 到 toIndex 之间的子集合(左闭右开区间)
* @throws IndexOutOfBoundsException {@inheritDoc} 对该子集合的操作,会影响原有集合
* @throws IllegalArgumentException {@inheritDoc} 当调用了 subList() 后,若对原有集合进行删除操作(删除subList 中的首个元素)时,会抛出异常 java.util.ConcurrentModificationException
*/
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
//检查传入索引的合法性
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size) //由于是左闭右开的,所以toIndex可以等于size
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}
//嵌套内部类:也实现了 RandomAccess,提供快速随机访问特性 这个是通过映射来实现的
private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent; //实际传入的是ArrayList本身
private final int parentOffset; // 相对于父集合的偏移量,其实就是 fromIndex
private final int offset; // 偏移量,默认是 0
int size; //SubList中的元素个数
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex; //原来的偏移量
this.offset = offset + fromIndex; //加了offset的偏移量
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
// 设置新值,返回旧值
public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
ArrayList.this.elementData[offset + index] = e;//从这一条语句可以看出:对子类设置元素,是直接操作父类设置的
return oldValue;
}
// 获取指定索引的元素
public E get(int index) {
rangeCheck(index);
checkForComodification();
return ArrayList.this.elementData(offset + index); //从这里可以看出,先通过index拿到在原来数组上的索引,再调用父类的添加方法实现添加
}
public int size() {
checkForComodification();
return this.size;
}
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
// 移除subList中的[fromIndex,toIndex)之间的元素
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
// 添加集合中的元素到subList结尾
public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c); //调用父类的方法添加集合元素
}
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize==0)
return false;
checkForComodification();
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
return true;
}
public Iterator<E> iterator() {
return listIterator();
}
// 返回从指定索引开始到结束的带有元素的list迭代器
public ListIterator<E> listIterator(final int index) {
checkForComodification();
rangeCheckForAdd(index);
final int offset = this.offset;
return new ListIterator<E>() {
int cursor = index;
int lastRet = -1;
int expectedModCount = ArrayList.this.modCount;
public boolean hasNext() {
return cursor != SubList.this.size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= SubList.this.size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[offset + (lastRet = i)];
}
public boolean hasPrevious() {
return cursor != 0;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[offset + (lastRet = i)];
}
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = SubList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[offset + (i++)]);
}
// update once at end of iteration to reduce heap write traffic
lastRet = cursor = i;
checkForComodification();
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
SubList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(offset + lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
SubList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
}
};
}
// 再次截取subList
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, offset, fromIndex, toIndex);
}
private void rangeCheck(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+this.size;
}
private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
// 获取一个分割器
public Spliterator<E> spliterator() {
checkForComodification();
return new ArrayListSpliterator<E>(ArrayList.this, offset,
offset + this.size, this.modCount);
}
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
action.accept(elementData[i]); //这里将所有元素都接受到Consumer中了,所有可以使用1.8中的方法直接获取每一个元素
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
* and <em>fail-fast</em> {@link Spliterator} over the elements in this
* list.
*
* <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
* {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
* Overriding implementations should document the reporting of additional
* characteristic values.
*
* @return a {@code Spliterator} over the elements in this list
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
// 基于索引的、二分的、懒加载的分割器
/** Index-based split-by-two, lazily initialized Spliterator */
static final class ArrayListSpliterator<E> implements Spliterator<E> {
private final ArrayList<E> list; //用于存放ArrayList对象
private int index; // current index, modified on advance/split /起始位置(包含),advance/split操作时会修改
private int fence; // -1 until used; then one past last index //结束位置(不包含),-1 表示到最后一个元素
private int expectedModCount; // initialized when fence set //用于存放list的modCount
/** Create new spliterator covering the given range *///默认的起始位置是0,默认的结束位置是-1
ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
int expectedModCount) {
this.list = list; // OK if null unless traversed
this.index = origin;
this.fence = fence;
this.expectedModCount = expectedModCount;
}
//在第一次使用时实例化结束位置
private int getFence() {
// initialize fence to size on first use
int hi; // (a specialized variant appears in method forEach)
ArrayList<E> lst;
if ((hi = fence) < 0) {
//fence<0时(第一次初始化时,fence才会小于0):
if ((lst = list) == null)
hi = fence = 0; //list 为 null时,fence=0
else {
expectedModCount = lst.modCount;
hi = fence = lst.size; //否则,fence = list的长度。 0 1 fence为2
}
}
return hi;
}
//分割list,返回一个新分割出的spliterator实例,二分法
public ArrayListSpliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;//hi:结束位置(不包括) lo:开始位置 mid:中间位置
return (lo >= mid) ? null : // divide range in half unless too small
new ArrayListSpliterator<E>(list, lo, index = mid, //当lo>=mid,表示不能在分割,返回null
expectedModCount); //当lo<mid时,可分割,切割(lo,mid)出去,同时更新index=mid
}
//返回true 时,只表示可能还有元素未处理 返回false 时,没有剩余元素处理了
public boolean tryAdvance(Consumer<? super E> action) {
if (action == null)
throw new NullPointerException();
int hi = getFence(), i = index;
if (i < hi) {
index = i + 1; //索引右移
@SuppressWarnings("unchecked") E e = (E)list.elementData[i];//取出元素
action.accept(e);//给Consumer类函数
if (list.modCount != expectedModCount) //遍历时,结构发生变更,抛错
throw new ConcurrentModificationException();
return true;
}
return false;
}
//顺序遍历处理所有剩下的元素
public void forEachRemaining(Consumer<? super E> action) {
int i, hi, mc; // hoist accesses and checks from loop
ArrayList<E> lst; Object[] a;
if (action == null)
throw new NullPointerException();
if ((lst = list) != null && (a = lst.elementData) != null) {
if ((hi = fence) < 0) {
//当fence<0时,表示fence和expectedModCount未初始化,
mc = lst.modCount;
hi = lst.size; //由于上面判断过了,可以直接将lst大小给hi(不包括)
}
else
mc = expectedModCount;
if ((i = index) >= 0 && (index = hi) <= a.length) {
for (; i < hi; ++i) {
//将所有元素给Consumer
@SuppressWarnings("unchecked") E e = (E) a[i];
action.accept(e);
}
if (lst.modCount == mc)
return;
}
}
throw new ConcurrentModificationException();
}
//估算大小
public long estimateSize() {
return (long) (getFence() - index);
}
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
//根据Predicate条件来移除元素 将所有元素依次根据filter的条件判断 Predicate 是 传入元素 返回 boolean 类型的接口
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
// figure out which elements are to be removed
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
//如果元素满足条件 true 会留下
removeSet.set(i); //将满足条件的角标存放到set中
removeCount++; //移除元素的个数
}
}
if (modCount != expectedModCount) {
//判断是否被外部修改了
throw new ConcurrentModificationException();
}
// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0; //如果有移除元素//如果有移除元素
if (anyToRemove) {
final int newSize = size - removeCount; //新大小
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i); //把removeSet的元素放回原来数组
elementData[j] = elementData[i]; //新元素
}
for (int k=newSize; k < size; k++) {
//将空元素置空
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
@Override
@SuppressWarnings("unchecked")
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);//取出每一个元素给operator的apply方法
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
//根据 Comparator条件进行排序
@Override
@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
}
总结几个关键的点
ArrayList使用无参构建函数创建是创建了一个空数组,名字是DEFAULTCAPACITY_EMPTY_ELEMENTDATA,然后第一次使用add()添加的时候才会进行扩容,这是懒加载方式
使用有参构造函数创建,如果参数是0就创建一个空数组,名字是EMPTY_ELEMENTDATA,如果参数大于0,就用这个参数创建一个数组
add()方法流程:
先看需不需要扩容:minCapacity加1,如果当前数组是空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA,就用默认容量和+1后的minCapacity比较,取最大值为minCapacity,否则不用比较,然后判断是否比当前数组的长度大,是的话就调用grow方法进行扩容
grow方法:
先取当前数组长度,新数组长度为当前数组长度1.5倍,然后判断新数组长度是否小于minCapacity,小于的话就用minCapacity作为新数组长度,如果新数组长度大于数组长度的上限,再判断minCapacity是否大于数组长度的上限,是的话就把MAX_VALUE作为新数组长度,否的话把数组长度的上限作为新数组长度,最后调用Arrays.copyOf()方法把旧数组的值移到扩容后的数组
流程图如下
源码里很多地方都用到了Array.copyOf()这个方法,例如删除和添加元素