编码到一定程度之后,希望自己进一步成长,那就只能通过阅读源码来提升自己。源码不敢说是最优的实现,那也得是比较优秀的实现了。楼主将开启自己的阅读源码之旅,为了让这段旅程能坚持更久,楼主决定从最简单的开始。所以本篇的主角就是ArrayList、虽然网上有大量的文章,对ArrayList实现也有个整体的概念,但我依然觉得有阅读的必要,我们依然可以看看有没有什么细节,需要我们去注意。
⚠️注意:本文的分析基于JDK1.8
一、构造函数
代码分析
通过构造函数,我们来看看ArrayList定义的时候,都做了什么操作。可以看到源码里面有三个构造函数、分别如下
//一个Object数组,用来存储存进来的对象,因为是Object类型的,所以ArrayList并不能存储基本类型数据
//transient 表示序列化的时候,不将该字段进行序列化,那ArrayList什么可以序列化呢?可以看看下面链接的文章
transient Object[] elementData;
//静态常量指向一个空数组
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//静态常量指向一个空数组
private static final Object[] EMPTY_ELEMENTDATA = {};
//无参构造函数
public ArrayList() {
//通过无参构造函数构建ArrayList,只会将数组变量指向一个空的数组。
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
传入一个初始容量,来构建ArrayList
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//如果传过来的数值大于0,则创建一个大小为传进来参数大小的数组。
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//如果传过来的数值等于0,则直接将数组引用直接指向一个空数组
this.elementData = EMPTY_ELEMENTDATA;
} else {
//传过来参数小于0,直接抛出异常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
通过传过来一个集合初始化ArrayList
*/
public ArrayList(Collection<? extends E> c) {
//将集合转为Object数组
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
//c.toArray 可能返回的不是Object数组,暂时不明白什么情况下返回的不是Object[]
if (elementData.getClass() != Object[].class)
//新建一个数组,元素复制于传进来的集合,赋值给elementData变量
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// 传进来集合长度为0,则将数组初始化为空数组
this.elementData = EMPTY_ELEMENTDATA;
}
}问:什么存储的数组被定义为transient,ArrayList还能序列化?
阶段总结:
ArrayList通过Object[]对象来存储数据,只能存对象类型数据,不能存基础类型。构造函数如果不传参数则直接初始化为空数组。传初始化容量,则初始化为传入的容量的数组。传一个集合,初始化为集合内容。
二、往ArrayList中加数据
代码分析
/**
*增加元素到尾部
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 确保数组长度够长,如果不够则扩容
//将元素放到数组中
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//calculateCapacity() 这个函数计算最小容量。即数组为空数组时返回10,否则为mingCapacity
//ensureExplicitCapacity函数将进行容量判断,如需要会进行扩容
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
/**
*计算最小容量
*如果第一次插进来数据,数组还没初始化,则默认为max(10,minCapacit),
*否则为传进来的参数
*/
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return 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);
//如果1.5倍还不够,则直接扩容到传进来的容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//如果容量超过Int的最大值,有些VM会抛出异常
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
//新建一个数组,容量为newCapacity,将就数组复制到新数组中
elementData = Arrays.copyOf(elementData, newCapacity);
}
阶段总结:
往List中增加元素:
(1)、如果List还未初始化则初始容量为 max(10,最小需要容量)。
(2)、如果数组已经初始化,并且剩余容量够存储,则直接将元素存在进去。
(3)、如果容量不够,则扩容为 max(原来容量1.5倍,最小需要容量)。
再看下往特定位置增加元素
public void add(int index, E element) {
//这个函数里面没什么东西,都是传进来的位置index大于已经存储的元素个数,则抛出异常。
rangeCheckForAdd(index);
//判断容量、扩展容量的,这个上面已经有说了
ensureCapacityInternal(size + 1); // Increments modCount!!
//将index位置后面的元素往后移,空出index位置,存放新添加进来的元素
System.arraycopy(elementData, index, elementData, index + 1,size - index);
elementData[index] = element;
size++;
}上面为增加单个元素的,再看看增加多个元素是怎么处理的?其实也是差不多的
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);
size += numNew;
return numNew != 0;
}三、删除ArrayList中的数据
1、删除指定位置元素
//指定位置删除元素
public E remove(int index) {
//如果index的位置大于目前已经存储的元素,直接抛出异常
rangeCheck(index);
modCount++;
//拿到当前index位置的数据
E oldValue = elementData(index);
//index后面的元素都需要往前移一位,计算需要往后移动的元素的数量
int numMoved = size - index - 1;
//index后面的元素往前移
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//最后空出来的位置值为null
elementData[--size] = null; // clear to let GC do its work
//返回旧的值
return oldValue;
}2、删除指定元素
public boolean remove(Object o) {
//如果是null,则比较用==
if (o == null) {
for (int index = 0; index < size; index++)
//查找出为null的元素位置index
if (elementData[index] == null) {
//删除index位置元素。将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;
}
//删除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
}
3、删除批量元素
public boolean removeAll(Collection<?> c) {
//如果传进来一个空的集合,抛出NullPointException
Objects.requireNonNull(c);
//批量删除list中的数据
return batchRemove(c, false);
}
//***************这里稍微要费点脑看看****************
//这个方法具体的思想就是把不删除的元素移动到数组前头,之后如果有元素需要被删除,则将数组后面位置置为null
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
//这个for循环的作用就是把不需要移除的元素复制到数组开头
/**
例子[7,9,0,6,8]删除[0,6],经过这个for循环的接口会是[7,9,8 ,6,8]
可以看到三个不需要删除的元素已经被移动数组开头位置,w会是3,指向第一个需要需要被值null的位置
*/
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
/**执行contains方法出现异常的情况,假设上面的例子循环到元素6的时候出现异常
例子[7,9,0,6,8]删除[0,6] for循环的结果还是[7,9,0,6,8] w会是2,r会是3
*/
if (r != size) {
/**抛出异常时,循环到的位置的元素及后面的元素,不再进行删除,于是只有0会被删除,这里就是
把元素6及后面的元素往前拷贝到w的位置,结果就成为[7,9,6,8,8]*/
System.arraycopy(elementData, r,
elementData, w,
size - r);
//w的值值为现在列表删除后应该剩下的元素个数,例子只删了0一个元素,所以w=4
w += size - r;
}
//有元素被删除,把最后的位置值为null
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;
}
阶段总结:
如果删除指定位置,或者删除传入的某个对象,上面的方法1,2,则定位到元素的位置,之后将要删除位置后面的元素往前移一位,将数组最后一个元素位置置为null。这个应该很好理解,数组删除元素就是移动元素。
如果删除指定集合中的元素,则将不需要删除的元素直接移动到数组开头位置,异常情况下,则移动到开头的包括两部分((1)异常发生位置前,不需要被删除的元素;(2)异常发生位置后面的所有元素),之后再将数组后面不需要的位置置为null
四、ArrayList中查找元素
代码分析
这个不用看代码,有没都知道它只能遍历数组去查
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**从前往后遍历,找指定元素,找不到则返回-1*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
/**从后面往前查找定位某元素位置,不存在则返回-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;
}五、List的拷贝
代码分析
/**
克隆出一个ArrayList,返回,这里返回的对象是克隆出来的新对象,
操作新对形象,并不会影响原来的ArrayList
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) 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(e);
}
}
/**
拷贝出一个新的数组返回
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
这个方法得注意下了:
(1)、传入的数组长度比ArrayList存储的元素个数小,则会返回一个新的数组,
传进来的数组并不会拷贝ArrayList中的元素
(2)、传进来的数组长度大于等于ArrayList中存储的元素个数,则只会将ArrayList中的元素拷贝到传进来的
数组里面,并返回该数组
*/
public <T> T[] toArray(T[] a) { if (a.length < size)
// 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);
if (a.length > size)
a[size] = null;
return a;
}阶段总结:
这里比较简单,不过得⚠️注意下toArray(T[] a)这个方法,可能一不小心会写出Bug。
六、看看迭代器
Iterator
/**
实现Iterator接口,ArrayList定义的内部类,迭代器类
*/
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
/**
这个很关键,modCount,上面的代码多次出现此变量,我们没做出解释.
其实他的用处是这里,每次修改List,modCount都会自增,
所以可以看做是ArrayList当前数据的版本,一会会用到.
*/
int expectedModCount = modCount;
Itr() {}
/**判断是否还有下一个值,如果游标不等于元素个数,则还有下一个值*/
public boolean hasNext() {
return cursor != size;
}
/**
拿到下一个值*
*/
@SuppressWarnings("unchecked")
public E next() {
/**上面说的版本号,就用到这里了,如果迭代器使用期间,
有其他线程修改了ArrayList,那么迭代器会直接抛出ConcurrentModificationException异常。
ArrayList是非线程安全的,迭代器采用快速失败的方法,一旦有线程修改数据,迭代就会失败。
*/
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() {
//lastRet 上一次返回元素位置,如果<0,说明还没有使用next遍历,直接抛出异常
if (lastRet < 0)
throw new IllegalStateException();
//并发抛出异常
checkForComodification();
try {
//删除指定位置的元素
ArrayList.this.remove(lastRet);
/*游标指向被删除元素位置,
例子:[5,7,9,6],删除7,调next返回7后,cursor此时应该是2,指向"9"的位置,lastRet为1,指向“7”
删除后列表为[5,9,6],cursor置为1,指向“9”
*/
cursor = lastRet;
lastRet = -1;
//修改迭代器版本号
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
/**
自动遍历游标之后的所有元素,交给consumer去处理
*/
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
//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里面遍历游标到结束位置的所有元素,交给consumer去处理
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();
}
//返回是否并发修改了ArrayList
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}List特有迭代器
/**实现ListIterator接口,继承自上面的Itr 遍历器,提供了从后往前遍历,还有修改元素,增加元素*/
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];
}
//修改元素,直接set一个元素过来
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//增加元素,调用add方法增加
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();
}
}阶段总结:
迭代器,这里代码也比较简单,要注意的主要有几个点:(1)、ArrayList是非线程安全的,一旦有其他线程修改了,迭代器采用快速失败的方法,直接抛出异常。(2)、ListItertor相对Itertor,除了往后遍历,还可以往前遍历。(3)、ListItertor比Itertor多了增加元素,修改元素的方法。
总结
到此,ArrayList的代码基本解析完毕,这里还需要明确的几个点:
(1)、ArrayList采用数组来存储,数组长度是是不允许扩展的,ArrayList扩展通过,创建一个新数组,并将旧数组元素拷贝到新数组,实现扩展。
(2)、数组结构存在意味着指定位置获取元素,是比较快的,时间复杂度是O(1),而删除元素、增加元素涉及元素移动,时间复杂度是O(n)。