ArrayList源码分析
前言:以下源码基于jdk20
一、add方法源码分析
// add方法入口
public boolean add(E e) {
//判断是否需要扩容,将当前arraylist的size+1(意味着即将新增一个元素)作为需要扩容的最小容量
ensureCapacityInternal(size + 1); // Increments modCount!!
//将元素追加到数组末尾
elementData[size++] = e;
return true;
}
//ensureCapacityInternal源码分析
//判断是否需要扩容
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
//calculateCapacity源码分析
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//如果数组是空数组(初始状态),比较默认容量(10)和需要扩容最小容量minCapacity大小,取最大值
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
//如果不是空数组(arraylist中有数据),返回需要扩容的最小容量minCapacity
return minCapacity;
}
//ensureExplicitCapacity源码分析
//精确扩容
private void ensureExplicitCapacity(int minCapacity) {
//记录arraylist修改次数(这个参数很重要,下面分析ConcurrentModificationException异常时会用到)
modCount++;
// overflow-conscious code
//如果 需要扩容的最小容量大于当前底层数组长度(意味着现有的数组已经无法存放新的数据了),则需要扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//grow源码分析
//真正实现扩容的逻辑
private void grow(int minCapacity) {
// overflow-conscious code
//获取原来的底层数组容量oldCapacity
int oldCapacity = elementData.length;
//基于oldCapacity进行扩容
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 如果新容量newCapacity小于需要扩容的容量minCapacity
if (newCapacity - minCapacity < 0)
//新容量指定为需要扩容的容量minCapacity
newCapacity = minCapacity;
//如果 新容量大于最大数组容量MAX_ARRAY_SIZE(默认为Integer.MAX_VALUE - 8)
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;
}
二、关于ConcurrentModificationException异常问题
话不多说,直接上代码
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer next = iterator.next();
list.remove(next);
}
}
//异常信息
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:911)
at java.util.ArrayList$Itr.next(ArrayList.java:861)
问题分析:
上述的场景就是在利用迭代器遍历集合时,使用了集合的remove方法,最终导致了异常。根本原因就是由于集合中有一个属性modCount和迭代器中的expectedModCount属性不一致。
源码分析:
ArrayList集合类继承自AbstractList抽象类,该类定义了集合的一些基本操作和属性,其中有一个属性叫modCount
/**
官方注释意思是这个变量代表该集合被改变结构的次数,诸如add、remove方法,都会改变该值
* The number of times this list has been <i>structurally modified</i>.
*/
protected transient int modCount = 0;
同时ArrayList集合类有一个公共方法iterator(),该方法返回一个Iterator迭代器用于遍历ArrayList集合,下图贴出了源码,并从源码的层面解释为什么上面的代码会抛出异常
public Iterator<E> iterator() {
//创建一个迭代器并返回,Itr类是ArrayList类的内部类
return new Itr();
}
//下图是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
//注意这个expectedModCount属性,很重要,初始化为modCount
int expectedModCount = modCount;
// prevent creating a synthetic constructor
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
//迭代器的next方法每次调用前都会校验expectedModCount是否和modCount相等,如果不相等则会抛出异常ConcurrentModificationException
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];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
//校验expectedModCount是否和modCount相等,如果不相等则会抛出异常ConcurrentModificationException
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
//注意这里,很关键,每次通过迭代器的remove方法删除了集合的元素后,会动态的设置expectedModCount = modCount,这就保证了下次再调用
//checkForComodification方法时,expectedModCount和modCount值是相同的,就不会抛出异常,所以如果使用迭代器遍历集合时,最好使用
//迭代器自带的操作集合元素的方法,如果使用集合自己的remove方法,是没法修改迭代器的expectedModCount值的,所以在迭代器调用next()方法
//获取下一个元素时,checkForComodification()方法就会检测到modCount != expectedModCount,导致异常
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
//校验expectedModCount是否和modCount相等,如果不相等则会抛出异常ConcurrentModificationException
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
//ArrayList集合自己的remove方法源码
public boolean remove(Object o) {
final Object[] es = elementData;
final int size = this.size;
int i = 0;
found: {
if (o == null) {
for (; i < size; i++)
if (es[i] == null)
break found;
} else {
for (; i < size; i++)
if (o.equals(es[i]))
break found;
}
return false;
}
//调用fastRemove方法
fastRemove(es, i);
return true;
}
private void fastRemove(Object[] es, int i) {
//注意这里,修改了modCount的值,并没有修改迭代器的expectedModCount,所以在迭代器调用next()方法
//获取下一个元素时,checkForComodification()方法就会检测到modCount != expectedModCount,导致异常
modCount++;
final int newSize;
if ((newSize = size - 1) > i)
System.arraycopy(es, i + 1, es, i, newSize - i);
es[size = newSize] = null;
}
好了源码看完了,我们再看以下上面的问题代码
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
//问题点1:调用迭代器的next方法(内部会校验modCount != expectedModCount)
Integer next = iterator.next();
//问题点2:调用集合的remove方法(内部会修改modCount,但是不修改expectedModCount,导致迭代器的next方法校验失败,抛出异常)
list.remove(next);
//如果改用迭代器的remove方法则不会有问题
//iterator.remove();
}
}
以上就是部分ArrayList源码解析,仅供参考哈 哈哈哈哈