ArrayList源码分析
集合结构图
对集合类的源码分析主要从一下几个方面进行:
- 常量
- 构造器
- 增、删、改、查
- 迭代器
常量
/**
* 默认的初始化容量
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 一个空数组
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 一个空数组
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 存放数据的数组
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* 大小
*/
private int size;
从上面的常量可以看出,ArrayList就是对数组的一个封装。
构造器
public ArrayList(int initialCapacity) {
//如果初始容量大于0,初始化成给定容量的数组
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//初始化容量等于0,给为空数组
this.elementData = EMPTY_ELEMENTDATA;
} else {
//初始化容量小于0,抛出异常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
public ArrayList() {
//先是给空数组,后面添加元素时给默认容量10
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
public ArrayList(Collection<? extends E> c) {
//先把集合转化为数组赋值给elementData
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
//如果elementData不是Object[]的类型。转换为Object[]类型
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
增
public boolean add(E e) {
//检查容量是否可用,不够进行扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
//赋值(数组赋值)
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//如果还没有初始化,默认初始化为10
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//检查是否需要扩容
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
//修改次数加一
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
//旧容量
int oldCapacity = elementData.length;
//新容量为原来的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:
elementData = Arrays.copyOf(elementData, newCapacity);
}
public void add(int index, E element) {
//检查添加的是否越界
rangeCheckForAdd(index);
//检查容量是否可用,不够进行扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
//将index后面的值向右移动,比如index为2,数组[1,2,3,4]移动后为[1,2,3,3,4]
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//index位置赋值为新值
elementData[index] = element;
//大小加1
size++;
}
public boolean addAll(Collection<? extends E> c) {
//转为数组
Object[] a = c.toArray();
//添加的集合大小
int numNew = a.length;
//检查容量是否可用,不够进行扩容
ensureCapacityInternal(size + numNew); // Increments modCount
//把添加的集合数据添加到数组里面
//把a数组从第0个位置开始,复制到elementData里面,从size位置开始添加,复制长度为numNew
System.arraycopy(a, 0, elementData, size, numNew);
//增加大小
size += numNew;
return numNew != 0;
}
public boolean addAll(int index, Collection<? extends E> c) {
//检查添加的是否越界
rangeCheckForAdd(index);
//添加的集合大小
Object[] a = c.toArray();
//添加的集合大小
int numNew = a.length;
//检查容量是否可用,不够进行扩容
ensureCapacityInternal(size + numNew); // Increments modCount
//需要移动的大小,比如[1,2,3,4,5,6]在index为2的位置添加,那么需要移动的就是4位,那就是[3,4,5,6]
int numMoved = size - index;
if (numMoved > 0)
//向右移动
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
//将需要添加的集合填充到数组里面
System.arraycopy(a, 0, elementData, index, numNew);
//大小增加
size += numNew;
return numNew != 0;
}
删
public E remove(int index) {
//检查下标是否越界
rangeCheck(index);
//修改次数加一
modCount++;
//得到要移除的值
E oldValue = elementData(index);
//移动的位数
int numMoved = size - index - 1;
//数组的移动操作
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//最后一位置为null
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
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;
}
//这个方法和remove数组下标的值是类似的
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
}
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
//移动的位数
int numMoved = size - toIndex;
//向右进行移动
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work.
//将移动掉的部分数据赋值为null,方便垃圾回收器进行回收
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
public boolean removeAll(Collection<?> c) {
//不为空处理
Objects.requireNonNull(c);
return batchRemove(c, false);
}
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传false,去除c里面有的值
//complement传true,保存c里面存在的值
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
//如果c.contains()发生了异常,r就不会等于size了,这时候就需要将r之后的值赋值过来
//比如elementData为[1,2,3,4,5,6,7,8,9] c为[4,5,6],这时候在8位置发生了异常
//这时候elementData为[1,2,3,7,5,6,7,8,9],r为7,w为4,就是把8、9移动到5、6;elementData为[1,2,3,7,8,9,7,8,9]
//w = 6
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;
}
改
public E set(int index, E element) {
//检查数组下标是否越界
rangeCheck(index);
//得到旧的值
E oldValue = elementData(index);
//替换新值
elementData[index] = element;
return oldValue;
}
查
public E get(int index) {
//检查数组下标是否越界
rangeCheck(index);
//直接就是操作数组得到值
return elementData(index);
}
迭代器
public Iterator<E> iterator() {
//返回一个迭代器对象
return new Itr();
}
private class Itr implements Iterator<E> {
//游标,存的是下一个值得下标
int cursor; // index of next element to return
//上次返回的值,-1表示上一次没有返回
int lastRet = -1; // index of last element returned; -1 if no such
//修改次数
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
//下一个节点不等于集合大小,说明还有下一个节点
return cursor != size;
}
@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();
//游标加1
cursor = i + 1;
//返回值
return (E) elementData[lastRet = i];
}
public void remove() {
//没有值可以移除
if (lastRet < 0)
throw new IllegalStateException();
//检查并发修改异常
checkForComodification();
try {
//移除值
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@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();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public ListIterator<E> listIterator() {
//返回一个向前和向后迭代的迭代器
return new ListItr(0);
}
//继承Itr,拥有了向前迭代的能力
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
//游标不能于0,就说明还能向前迭代
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();
}
}
}
只要看懂了增、删、改、查这几个模块,迭代器部分就很好理解,不做过多的解释。