public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
// 版本序列号
private static final long serialVersionUID = 8683452581122892189L;
// ArrayList基于该数组实现,用该数组保存数据
private transient Object[] elementData;
// arraylist中实际数据的数量
private int size;
// ArrayList带容量大小的构造函数
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
// 新建一个数组
this.elementData = new Object[initialCapacity];
}
// ArrayList无参构造函数。默认容量是10。
public ArrayList() {
// this(10)等于ArrayList(10),即在调用带容量大小的构造函数
this(10);
}
// 创建一个包含collection的ArrayList
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
// 如果elementData不为Object数组类型,强制转换成Object数组类型
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
// 将当前容量值设为实际元素个数
public void trimToSize() {
//将“修改统计数”+1,该变量主要是用来实现fail-fast机制
modCount++;// —————————————————————————————————————————————————————————————————————在哪定义的?????———————————————————————————
int oldCapacity = elementData.length;
// 如果size小于容量值,就将容量缩小,
if (size < oldCapacity) {
elementData = Arrays.copyOf(elementData, size);
}
}
//************************************************************************************************确保容量的代码****************
// 确定ArrarList的容量。
// 若ArrayList的容量不足以容纳当前的全部元素,设置 新的容量=“(原始容量x3)/2 + 1”
public void ensureCapacity(int minCapacity) {
if (minCapacity > 0)
//
ensureCapacityInternal(minCapacity);
}
private void ensureCapacityInternal(int minCapacity) {
//将“修改统计数”+1,该变量主要是用来实现fail-fast机制
modCount++;
// overflow-conscious code
//若当前容量不足以容纳当前元素个数,执行增长容量
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//(oldCapacity>>1)表示数除以2,缩小为原来的2倍,再取整后加上自身,即完成了公式(oldCapacity*3)/2+1
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果还不够,则直接将minCapacity设置为当前容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//如果新容量大于最大数组界限,则minCapacity设置为当前容量
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();
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
//********************************************************************************************确保容量代码结束*************************************
public int size() {
return size;
}
public boolean isEmpty() {
//用size的值与0比较,若等于0,就是为空,否则为非空
return size == 0;
}
public boolean contains(Object o) {
//返回对象的下标,若下标不小于0,即存在合理的下标,表示存在该对象
return indexOf(o) >= 0;
}
//往往有很多方法需要用到类似的代码,只是在方法名上需要有一点点变动,则会有方法调用方法的情况,千万别再写重复代码**************************************************************
//正向查找
public int indexOf(Object o) {
//若传入对象为null,并且在数组中也包含null,则返回null的下标
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i] == null)
return i;
}
//若传入对象不为null,则遍历数组元素,相等则返回下标,否则返回-1
else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
//反向查找,返回元素的索引值,必然是一找到就返回,所以只要找到就是最尾端的元素,所以是最后的下标值
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,利用arrays。copyof复制过去,然后返回
public Object clone() {
try {
@SuppressWarnings("unchecked")
ArrayList<E> v = (ArrayList<E>) 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();
}
}
//转换成array数组,又是利用arrays.copyof函数
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
// 返回ArrayList元素组成的数组
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
// 若数组a的大小 < ArrayList的元素个数;
// 则新建一个T[]数组,数组大小是“ArrayList的元素个数”,并将“ArrayList”全部拷贝到新数组中
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
// 若数组a的大小 >= ArrayList的元素个数;
// 则将ArrayList的全部元素都拷贝到数组a中
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
// Positional Access Operations
// 获取index位置的元素值
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
// 获取index位置的元素值
public E get(int index) {
//范围检查,如果在范围内则继续
rangeCheck(index);
//返回指定位置的元素
return elementData(index);
}
// 设置index位置的值为element
public E set(int index, E element) {
//范围检查
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
//返回的是index位置上原有的数据
return oldValue;
}
// 将e添加到ArrayList中
public boolean add(E e) {
//添加元素之前先对容量进行确保
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
// 将e添加到ArrayList的指定位置
public void add(int index, E element) {
//检测范围,防止越界
rangeCheckForAdd(index);
//添加元素之前先对容量进行确保
ensureCapacityInternal(size + 1); // Increments modCount!!
//从指定位置开始复制size-index个元素,然后将index元素置为element,再将size++——————————————————————————————————————————————————————————————————
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
//这里需要满足两个条件,1.arrayList能动态扩容 2.经过容量确保后的arrayList总是非饱和状态——————————————————————————————————————————————————————————————
size++;
}
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
//因为少移动一个元素,少移动的那个元素就是被删除的元素。所以需要size-index-1
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
//难道设置为null时候,gc就知道了要去回收?????————————————————————————————————————————————————————————————————————————————————————————————
elementData[--size] = null; // Let gc do its work
return oldValue;
}
//先找到指定元素再删除,成功删除返回true,否则返回false,其中删除工作调用fastremove函数
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 void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
// 从"index+1"开始,用后面的元素替换前面的元素。
if (numMoved > 0)
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
// 将最后一个元素设为null
elementData[--size] = null; // Let gc do its work
}
//遍历数组,所有的下标里面的值全部设置为null,然后由垃圾回收机制进行回收
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
// 将集合c追加到ArrayList中
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
//容量确保
ensureCapacityInternal(size + numNew); // Increments modCount
//数组copy
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
// 从index位置开始,将集合c添加到ArrayList
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;
//将index开始的下标直到size位置的所有数据向后移动c的大小。留出空位给c集合进行复制
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
//将a集合copy到已留空位中
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
// 删除fromIndex到toIndex之间的全部元素
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
//从toindex位置开始,将后续元素往前移动toindex-fromindex个单位
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
//然后将最后面的toindex-fromindex个位置置为null,交给垃圾回收机制进行回收
// Let gc do its work
int newSize = size - (toIndex - fromIndex);
while (size != newSize)
elementData[--size] = null;
}
//范围检查
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//范围检查
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//溢出提示
private String outOfBoundsMsg(int index) {
return "Index: " + index + ", Size: " + size;
}
//移除c里面的所有,调用函数batchRemove————————————————————————————————————————————————————————————————————————————————————————————————
public boolean removeAll(Collection<?> c) {
return batchRemove(c, false);
}
//保留c里面的全部,调用函数batchRemove
public boolean retainAll(Collection<?> c) {
return batchRemove(c, true);
}
//************************************************************************************精华代码********************************
//第一想法是双重循环,若能面向对象考虑,则是把内循环放在c里面,变成下面代码中的c.contains函数
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++)
//使用一个complement标记来判断是否包含元素,若complement为true,则保留包含的;若complement为false,则保留不包含的,就是删除
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
//r不等于size的情况只有一种,就是当c。contains函数出现异常,这样的话,就将r往后的元素全部复制到w后面,挽救后面的数据,而已经筛选过的数据就不用管了,同时将w变成新数组大小
if (r != size) {
System.arraycopy(elementData, r, elementData, w, size - r);
w += size - r;
}
//若w与size不等,则将后面的所有单元设置为null,让垃圾回收机制进行回收,其实w是肯定小于size的,除非lis与c并无交集
if (w != size) {
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
//************************************************************************************************************
// java.io.Serializable的写入函数
// 将ArrayList的“容量,所有的元素值”都写入到输出流中
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 array length
s.writeInt(elementData.length);
// 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.Serializable的读取函数:根据写入方式读出
// 先将ArrayList的“容量”读出,然后将“所有的元素值”读出
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in array length and allocate array
// 从输入流中读取ArrayList的“容量”
int arrayLength = s.readInt();
Object[] a = elementData = new Object[arrayLength];
// Read in all elements in the proper order.
// 从输入流中将“所有的元素值”读出
for (int i = 0; i < size; i++)
a[i] = s.readObject();
}
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index);
return new ListItr(index);
}
public ListIterator<E> listIterator() {
return new ListItr(0);
}
// 返回List对应迭代器。实际上,是返回Itr对象。
public Iterator<E> iterator() {
return new Itr();
}
//内部类 Itr是Iterator(迭代器)的实现类
private class Itr implements Iterator<E> {
//并没有赋值,是默认为0了?????????????????????????????????????????????????***************************
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
// 修改数的记录值。
// 每次新建Itr()对象时,都会保存新建该对象时对应的modCount;
// 以后每次遍历List中的元素的时候,都会比较expectedModCount和modCount是否相等;
// 若不相等,则抛出ConcurrentModificationException异常,产生fail-fast事件。
int expectedModCount = modCount;
//若计数器与集合大小不等,说明还有下一个元素,否则无下一个元素
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
// 获取下一个元素之前,都会判断“新建Itr对象时保存的modCount”和“当前的modCount”是否相等;
// 若不相等,则抛出ConcurrentModificationException异常,产生fail-fast事件。
//————————————————————————————————————————————————这里是实现fast-fail的真实调用函数————————————————————————————————————
checkForComodification();
//——————————————————————————————————————————————————————————————————————————————————————————
//每运行一次next方法都要给i赋值??而不是直接用cursor计数?多线程也不会影响到cursor这个值啊!有点多余的感觉********************************
//好像懂了,next函数返回值时要返回当前元素,返回后要对指针加1指向下一个元素。用一个变量的话,返回后就不能进行加1操作了,因为已经return了。所以用两变量
//并且由于是函数内部的变量i,调用结束后垃圾回收机制会自动回收内存。
int i = cursor;
//计数器比size大,越界!抛出无此元素异常
if (i >= size)
throw new NoSuchElementException();
//具体实例的实现数组元素
Object[] elementData = ArrayList.this.elementData;
//elementData的长度与size不等,是因为arraylist是动态数组,并不会存满,
if (i >= elementData.length)
throw new ConcurrentModificationException();
//让计数器加1,然后返回当前元素。
cursor = i + 1;
return (E) elementData[lastRet = i];
}
//删除元素
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
//fast-fail检测
checkForComodification();
//因为删除元素实质上是对arraylist进行写操作,写操作就会改变modCount值。也就可能触发多线程异常机制
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//——————————————————————————————————————————fast-fail机制的实现代码,就是抛出一个异常————————————————————————————————————————————————————————————
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
//————————————————————————————————————————————————————————————————————————————————————————————————————
}
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;
}
public int previousIndex() {
return cursor - 1;
}
@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;
return (E) elementData[lastRet = i];
}
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);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new 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)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
}
//取子列表,较简单的内部类
private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent;
//偏移量
private final int parentOffset;
private final int offset;
int size;
//构造函数
SubList(AbstractList<E> parent, int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
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);
}
//检查,返回size
public int size() {
checkForComodification();
return this.size;
}
//两个检查,添加值,操作计数设置,范围加1
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
//两个检查,删除元素,操作次数设置,范围减1
public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
//范围删除,线程安全检查,删除范围,操作次数设置,范围缩小
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
parent.removeRange(parentOffset + fromIndex, parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
//添加所有。
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();
}
//内部迭代类,实现原理和ArrayList的迭代器的原理相同,只是在计数器上赋值了。那代码是不是有点重复呢??????????????????
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)];
}
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();
}
};
}
//带偏移量的取子列表
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();
}
}
}
【JDK源码】JDK/ArrayList源码逐行详解
深入解析ArrayList的内部实现
最新推荐文章于 2025-07-27 00:40:25 发布
本文详细探讨了ArrayList类的内部实现机制,包括其构造、元素操作、容量管理及序列化过程,旨在帮助开发者理解这一常用数据结构的底层逻辑。
1076

被折叠的 条评论
为什么被折叠?



