一、概述
此类提供的骨干实现的List接口以最小化来实现该接口由一个“随机访问”数据存储备份所需的工作(如阵列)。要实现一个不可修改的列表,只需要继承这个类并提供get(int)和size()方法的实现。要实现可修改的列表,必须另外覆盖set(int, E)方法(否则会抛出一个UnsupportedOperationException )。如果列表是可变大小,则我们必须另外覆盖add(int, E)和remove(int)方法。继承结构如下图:
二、源码分析
(1) 类的声明源码如下:
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>{}
AbstractList类是一个抽象类,不能被实例化,它继承自AbstractCollection类并且实现了List类。
(2) 成员变量源码如下:
//此列表已被结构修改的次数。
protected transient int modCount = 0;
modCount在AbstractList子类中,当在遍历过程中调用了集合的add,remove方法时,modCount就会改变,而迭代器记录的modCount是开始迭代之前的,如果两个不一致,就会报异常,说明有两个线路(线程)同时操作集合。这种操作有风险,为了保证结果的正确性, 避免这样的情况发生,一旦发现modCount与expectedModCount不一致,立即报错,这就是为了实现快速失败。
(3) AbstractList类中,直接调用add(), set(), remove()方法会抛异常,所以子类需要自己重写,源码如下:
public boolean add(E e) {
add(size(), e);
return true;
}
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
(4) indexOf()方法,源码如下:
public int indexOf(Object o) {
//获取迭代器
ListIterator<E> it = listIterator();
//从0开始一直向后找,找到则返回元素所在位置
if (o==null) {
//向后遍历,判断是否存在下一个对象
while (it.hasNext())
if (it.next()==null)
return it.previousIndex();
} else {
while (it.hasNext())
if (o.equals(it.next()))
return it.previousIndex();
}
//未找到则返回-1
return -1;
}
public int previousIndex() {
return cursor-1;
}
此方法返回的是对象首次出现的位置。值得注意的是,it.hasNext()方法在执行的时候,listIterator的游标(也可以理解成标记的下一个位置)已经成为了下一个元素的位置,所以当查询到目标对象后,返回了it.previousIndex()方法,也就是it的前一个位置的游标。
(5) lastIndexOf()方法,源码如下:
public int lastIndexOf(Object o) {
ListIterator<E> it = listIterator(size());
if (o==null) {
//向前遍历,判断是否有前一个元素
while (it.hasPrevious())
if (it.previous()==null)
return it.nextIndex();
} else {
while (it.hasPrevious())
if (o.equals(it.previous()))
return it.nextIndex();
}
return -1;
}
public int nextIndex() {
return cursor;
}
此方法返回的是此对象最后出现的位置。与indexOf()方法不同的是,lastIndexOf()方法是向前迭代,也就是从后往前找,找到目标对象, 就返回it.nextIndex()方法,,也就是it的后一个位置的游标。
(6) clear()方法与removeRange()方法都是删除元素,源码如下:
public void clear() {
removeRange(0, size());
}
//有起止位置的移除
protected void removeRange(int fromIndex, int toIndex) {
ListIterator<E> it = listIterator(fromIndex);
for (int i=0, n=toIndex-fromIndex; i<n; i++) {
it.next();
it.remove();
}
}
(7) AbstractList类有两个内部类 Iterator, ListIterator ,它们都是迭代器的实现类,分别为 Itr,ListItr。Itr 只是简单实现了 Iterator 的 next(),remove()方法。ListItr在 Itr基础上多了previousIndex()和set()。那么我们先来看一下Itr的源码,如下:
private class Itr implements Iterator<E> {
//默认游标
int cursor = 0;
//用于记录上一次迭代的元素的位置,用完重置为-1
int lastRet = -1;
//expectedModCount 用于与AbstractList类中的modCount比较来判断是否发生了并发情况,用户快速失败
int expectedModCount = modCount;
//判断是否存在下一个元素,游标值不是List的元素数量,说明有下个元素。
public boolean hasNext() {
return cursor != size();
}
//获取下一个元素
public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
//记录上一次迭代的元素位置
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
//
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
//当modCount和expectedModCount值不一样时,说明出现了并发量过高,导致出现了异步修改。需要抛出异常
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
//检查是否发生了并发
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
依照上文所述,Itr确实只是简单实现了Iterator的next(),remove()方法。
(8) ListItr类的源码如下:
private class ListItr extends Itr implements ListIterator<E> {
//构造函数指定初始游标
ListItr(int index) {
cursor = index;
}
//判断是否有上一个元素,游标为0前就都有
public boolean hasPrevious() {
return cursor != 0;
}
//提供先前获取元素的方法
public E previous() {
checkForComodification();
try {
int i = cursor - 1;
E previous = get(i);
lastRet = cursor = i;
return previous;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
//获取下一个元素的坐标
public int nextIndex() {
return cursor;
}
//获取向前元素的坐标,也就是上一个元素的坐标,是游标-1,结合AbstractList类的IndexOf()方法更容易理解
public int previousIndex() {
return cursor-1;
}
//替换元素
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.set(lastRet, e);
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//添加元素
public void add(E e) {
checkForComodification();
try {
int i = cursor;
AbstractList.this.add(i, e);
lastRet = -1;
cursor = i + 1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
ListItr类在继承Itr的基础上多了获取向前元素和set()方法。 ListItr中lastRet的作用是保证在add或者remove后不能继续remove元素。remove后当前元素不存在了,自然不能继续remove当前元素;add之后游标指向了下一个元素,cursor + 1,需要next之后继续添加。
(9) AbstractList类文件中还定义了两个同级类SubList类和RandomAccessSubList类。我们挨着分析一下源码来探究它们存在的意义。SubList类源码如下:
//AbstractList 的子类,表示父 List 的一部分
class SubList<E> extends AbstractList<E> {
private final AbstractList<E> l;
private final int offset;
private int size;
//构造函数,subList()方法截取字符串也是调用自身的构造函数
SubList(AbstractList<E> list, int fromIndex, int toIndex) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > list.size())
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
l = list;
offset = fromIndex;
size = toIndex - fromIndex;
//与父类共用
this.modCount = l.modCount;
}
//替换元素
public E set(int index, E element) {
rangeCheck(index);
checkForComodification();
return l.set(index+offset, element);
}
//获取元素
public E get(int index) {
rangeCheck(index);
checkForComodification();
return l.get(index+offset);
}
//获取链表长度
public int size() {
checkForComodification();
return size;
}
//添加元素
public void add(int index, E element) {
rangeCheckForAdd(index);
checkForComodification();
l.add(index+offset, element);
this.modCount = l.modCount;
size++;
}
//移除元素
public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = l.remove(index+offset);
this.modCount = l.modCount;
size--;
return result;
}
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
l.removeRange(fromIndex+offset, toIndex+offset);
this.modCount = l.modCount;
size -= (toIndex-fromIndex);
}
//添加一个集合全部元素
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
//添加一个集合的部分元素
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize==0)
return false;
checkForComodification();
l.addAll(offset+index, c);
this.modCount = l.modCount;
size += cSize;
return true;
}
public Iterator<E> iterator() {
return listIterator();
}
public ListIterator<E> listIterator(final int index) {
checkForComodification();
rangeCheckForAdd(index);
return new ListIterator<E>() {
//创建一个 匿名内部 ListIterator,指向的还是 父类的 listIterator
private final ListIterator<E> i = l.listIterator(index+offset);
public boolean hasNext() {
return nextIndex() < size;
}
public E next() {
if (hasNext())
return i.next();
else
throw new NoSuchElementException();
}
public boolean hasPrevious() {
return previousIndex() >= 0;
}
public E previous() {
if (hasPrevious())
return i.previous();
else
throw new NoSuchElementException();
}
public int nextIndex() {
return i.nextIndex() - offset;
}
public int previousIndex() {
return i.previousIndex() - offset;
}
public void remove() {
i.remove();
SubList.this.modCount = l.modCount;
size--;
}
public void set(E e) {
i.set(e);
}
public void add(E e) {
i.add(e);
SubList.this.modCount = l.modCount;
size++;
}
};
}
//截取一段集合
public List<E> subList(int fromIndex, int toIndex) {
return new SubList<>(this, fromIndex, toIndex);
}
//检查下标是否合法
private void rangeCheck(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
//检查是否发生了并发修改
private void checkForComodification() {
if (this.modCount != l.modCount)
throw new ConcurrentModificationException();
}
}
SubList类里大多数方法都是调用的父类的方法,所以我们可以通过它间接操作父类的list。
(10) 最后再来看一下RandomAccessSubList类,源码如下:
class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
super(list, fromIndex, toIndex);
}
public List<E> subList(int fromIndex, int toIndex) {
return new RandomAccessSubList<>(this, fromIndex, toIndex);
}
}
RandomAccessSubList类实现了RandomAccess接口,RandomAccess接口也是标记接口,表示实现它的类支持快速随机访问。在使用循环遍历List的时候应该判断下这个集合是否是RandomAccess的实例,如果是就是用for循环来操作,如果不是就是使用iterator迭代器来操作。随机访问一般是通过index下标访问,行为类似数组的访问。而顺序访问类似于链表的访问,通常为迭代器遍历。以List接口及其实例为例。ArrayList是典型的随机访问型,而LinkedList则是顺序访问型。
三、总结
AbstractList类是重要list类的祖先,它实现了List类并且继承了AbstractCollection类,内部创建了两个迭代器Itr和ListItr,还声明了两个子类SubList和RandomAccessSublist,为后面学习其他重要的集合类打下坚实的基础。那么敬请期待《我的jdk源码(九):AbstractMap Map家族的骨架实现类》。
更多精彩内容,敬请扫描下方二维码,关注我的微信公众号【Java觉浅】,获取第一时间更新哦!