前言

AbstractList是实现List接口的一个抽象类,它的地位之与List类似于AbstractCollection之与Collection,同事,AbstractList继承了AbstractCollection,并针对List接口给出了一些默认的实现。而且它是针对随机访问储存数据的方式的,如果需要使用顺序访问储存数据方式,还有一个AbstractSequentialListAbstractList的子类,顺序访问时应该优先使用它。

框架图

Java基础系列(四十二):集合之AbstractList - 图1

源码

接下来,我们来看一下AbstractList的源码,看看他针对于List接口相较于AbstractCollection给出了哪些不同的实现方法。

  1. package java.util;
  2. public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
  3. //只提供了一个protected修饰的无参构造器,供子类使用。
  4. protected AbstractList() {
  5. }
  6. //添加一个元素,实际上并没有实现。
  7. public boolean add(E e) {
  8. //实际上,size()在这个方法中并没有实现,交由子类去实现。
  9. add(size(), e);
  10. return true;
  11. }
  12. //抽象方法,需要子类去实现,根据索引值获取集合中的某个元素(随机访问)
  13. abstract public E get(int index);
  14. //由于该集合是不可变的,所以一切可能会改变集合元素的操作都会抛出一个UnsupportedOperationException()
  15. public E set(int index, E element) {
  16. throw new UnsupportedOperationException();
  17. }
  18. public void add(int index, E element) {
  19. throw new UnsupportedOperationException();
  20. }
  21. public E remove(int index) {
  22. throw new UnsupportedOperationException();
  23. }
  24. // Search Operations
  25. //获取某个元素在集合中的索引
  26. public int indexOf(Object o) {
  27. //这里是由AbstractList内部已经提供了Iterator, ListIterator迭代器的实现类,分别为Itr,ListItr。这里是调用了一个实例化ListItr的方法
  28. ListIterator<E> it = listIterator();
  29. if (o==null) {
  30. while (it.hasNext())
  31. if (it.next()==null)
  32. return it.previousIndex();
  33. } else {
  34. while (it.hasNext())
  35. if (o.equals(it.next()))
  36. return it.previousIndex();
  37. }
  38. //如果集合中不存在该元素,返回-1
  39. return -1;
  40. }
  41. //获取某个元素在集合中最后一次出现的索引
  42. public int lastIndexOf(Object o) {
  43. ListIterator<E> it = listIterator(size());
  44. if (o==null) {
  45. while (it.hasPrevious())
  46. if (it.previous()==null)
  47. return it.nextIndex();
  48. } else {
  49. while (it.hasPrevious())
  50. if (o.equals(it.previous()))
  51. return it.nextIndex();
  52. }
  53. return -1;
  54. }
  55. // Bulk Operations
  56. //清除集合中的元素
  57. public void clear() {
  58. removeRange(0, size());
  59. }
  60. //从某个索引开始,将c中的元素全部插入到集合中
  61. public boolean addAll(int index, Collection<? extends E> c) {
  62. rangeCheckForAdd(index);
  63. boolean modified = false;
  64. for (E e : c) {
  65. add(index++, e);
  66. modified = true;
  67. }
  68. return modified;
  69. }
  70. // Iterators
  71. //获取Iterator接口Itr实现类迭代器
  72. public Iterator<E> iterator() {
  73. return new Itr();
  74. }
  75. //获取从0开始(初始位置)的ListIterator的实现类ListItr
  76. public ListIterator<E> listIterator() {
  77. return listIterator(0);
  78. }
  79. //获取从索引等于index的位置的迭代器
  80. public ListIterator<E> listIterator(final int index) {
  81. rangeCheckForAdd(index);
  82. return new ListItr(index);
  83. }
  84. /**
  85. * 内部实现了Iterator接口的实现类Itr
  86. */
  87. private class Itr implements Iterator<E> {
  88. //光标位置
  89. int cursor = 0;
  90. //上一次迭代到的元素的光标位置,如果是末尾会置为-1
  91. int lastRet = -1;
  92. //并发标志,如果两个值不一致,说明发生了并发操作,就会报错
  93. int expectedModCount = modCount;
  94. //判断是否存在下一条数据,即迭代器的位置是否走到尾
  95. public boolean hasNext() {
  96. //如果光标位置不等于集合个数,说明迭代器没有走到末尾,返回true
  97. return cursor != size();
  98. }
  99. //获取下一个元素
  100. public E next() {
  101. //判断是否有并发操作
  102. checkForComodification();
  103. try {
  104. int i = cursor;
  105. //通过索引位置来获取元素
  106. E next = get(i);
  107. lastRet = i;
  108. //每次将+1,将迭代器位置向后移动一位
  109. cursor = i + 1;
  110. return next;
  111. } catch (IndexOutOfBoundsException e) {
  112. //时刻检查是否有并发操作
  113. checkForComodification();
  114. throw new NoSuchElementException();
  115. }
  116. }
  117. //删除上一次迭代器越过的元素
  118. public void remove() {
  119. if (lastRet < 0)
  120. throw new IllegalStateException();
  121. checkForComodification();
  122. try {
  123. //调用需要子类去实现的remove方法
  124. AbstractList.this.remove(lastRet);
  125. if (lastRet < cursor)
  126. cursor--;
  127. //每次删除后,将lastRet置为-1,防止连续的删除
  128. lastRet = -1;
  129. //将修改次数赋给迭代器对对象的结构修改次数这个会在下面进行详解
  130. expectedModCount = modCount;
  131. } catch (IndexOutOfBoundsException e) {
  132. //如果出现索引越界,说明发生了并发的操作导致,所以抛出一个并发操作异常。
  133. throw new ConcurrentModificationException();
  134. }
  135. }
  136. //判断是否发生了并发操作
  137. final void checkForComodification() {
  138. if (modCount != expectedModCount)
  139. throw new ConcurrentModificationException();
  140. }
  141. }
  142. //继承自Itr的ListIterator的实现类ListItr
  143. private class ListItr extends Itr implements ListIterator<E> {
  144. //指定光标位置等于索引的迭代器构造
  145. ListItr(int index) {
  146. cursor = index;
  147. }
  148. //如果不是第一位,返回true
  149. public boolean hasPrevious() {
  150. return cursor != 0;
  151. }
  152. //获取上一位的元素,这里在后面会有画图帮助理解
  153. public E previous() {
  154. checkForComodification();
  155. try {
  156. //这里和父类的写法略有不同,先将光标的位置进行减一
  157. int i = cursor - 1;
  158. E previous = get(i);
  159. //因为需要返回的是前一位的元素,所以这里的光标值和上一次迭代到的光标的位置实际上是一样的
  160. lastRet = cursor = i;
  161. return previous;
  162. } catch (IndexOutOfBoundsException e) {
  163. checkForComodification();
  164. throw new NoSuchElementException();
  165. }
  166. }
  167. //下一位的索引值等于光标值
  168. public int nextIndex() {
  169. return cursor;
  170. }
  171. //上一位的索引值等于光标值减一
  172. public int previousIndex() {
  173. return cursor-1;
  174. }
  175. //设置元素
  176. public void set(E e) {
  177. if (lastRet < 0)
  178. throw new IllegalStateException();
  179. checkForComodification();
  180. try {
  181. //默认设置的位置是上一次迭代器越过的元素
  182. AbstractList.this.set(lastRet, e);
  183. expectedModCount = modCount;
  184. } catch (IndexOutOfBoundsException ex) {
  185. throw new ConcurrentModificationException();
  186. }
  187. }
  188. //添加元素
  189. public void add(E e) {
  190. checkForComodification();
  191. try {
  192. //设置添加的位置为当前光标所在的位置
  193. int i = cursor;
  194. AbstractList.this.add(i, e);
  195. //这里讲lastRet设置为-1,即添加的元素不允许立即删除
  196. lastRet = -1;
  197. //添加后,将光标移到
  198. cursor = i + 1;
  199. //迭代器并发标志和集合并发标志统一
  200. expectedModCount = modCount;
  201. } catch (IndexOutOfBoundsException ex) {
  202. //如果出现了索引越界,说明发生了并发操作
  203. throw new ConcurrentModificationException();
  204. }
  205. }
  206. }
  207. //切取子List
  208. public List<E> subList(int fromIndex, int toIndex) {
  209. //是否支持随机访问
  210. return (this instanceof RandomAccess ?
  211. new RandomAccessSubList<>(this, fromIndex, toIndex) :
  212. new SubList<>(this, fromIndex, toIndex));
  213. }
  214. // Comparison and hashing
  215. //通过迭代器来遍历进行判断每项是否相等来重写equals方法
  216. public boolean equals(Object o) {
  217. if (o == this)
  218. return true;
  219. if (!(o instanceof List))
  220. return false;
  221. ListIterator<E> e1 = listIterator();
  222. ListIterator<?> e2 = ((List<?>) o).listIterator();
  223. while (e1.hasNext() && e2.hasNext()) {
  224. E o1 = e1.next();
  225. Object o2 = e2.next();
  226. if (!(o1==null ? o2==null : o1.equals(o2)))
  227. return false;
  228. }
  229. return !(e1.hasNext() || e2.hasNext());
  230. }
  231. //重写hashCode
  232. public int hashCode() {
  233. int hashCode = 1;
  234. for (E e : this)
  235. hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
  236. return hashCode;
  237. }
  238. //使用迭代器成段删除集合中的元素
  239. protected void removeRange(int fromIndex, int toIndex) {
  240. ListIterator<E> it = listIterator(fromIndex);
  241. for (int i=0, n=toIndex-fromIndex; i<n; i++) {
  242. it.next();
  243. it.remove();
  244. }
  245. }
  246. //?
  247. protected transient int modCount = 0;
  248. //判断索引是否越界
  249. private void rangeCheckForAdd(int index) {
  250. if (index < 0 || index > size())
  251. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  252. }
  253. private String outOfBoundsMsg(int index) {
  254. return "Index: "+index+", Size: "+size();
  255. }
  256. }
  257. //继承自AbstractList的内部类SubList,代表了它父类的一部分
  258. class SubList<E> extends AbstractList<E> {
  259. private final AbstractList<E> l;
  260. private final int offset;
  261. private int size;
  262. //根据父类来构造一个SubList
  263. SubList(AbstractList<E> list, int fromIndex, int toIndex) {
  264. if (fromIndex < 0)
  265. throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
  266. if (toIndex > list.size())
  267. throw new IndexOutOfBoundsException("toIndex = " + toIndex);
  268. if (fromIndex > toIndex)
  269. throw new IllegalArgumentException("fromIndex(" + fromIndex +
  270. ") > toIndex(" + toIndex + ")");
  271. l = list;
  272. offset = fromIndex;
  273. size = toIndex - fromIndex;
  274. //修改次数(并发标志)和父类保持一致
  275. this.modCount = l.modCount;
  276. }
  277. //实际上还是调用的父类的set方法和get方法
  278. public E set(int index, E element) {
  279. rangeCheck(index);
  280. checkForComodification();
  281. return l.set(index+offset, element);
  282. }
  283. public E get(int index) {
  284. rangeCheck(index);
  285. checkForComodification();
  286. return l.get(index+offset);
  287. }
  288. //size = toIndex - fromIndex;
  289. public int size() {
  290. checkForComodification();
  291. return size;
  292. }
  293. public void add(int index, E element) {
  294. rangeCheckForAdd(index);
  295. checkForComodification();
  296. //实际上还是在父类上进行添加
  297. l.add(index+offset, element);
  298. this.modCount = l.modCount;
  299. //然后把size + 1
  300. size++;
  301. }
  302. public E remove(int index) {
  303. rangeCheck(index);
  304. checkForComodification();
  305. //实际上还是在父类上进行删除
  306. E result = l.remove(index+offset);
  307. this.modCount = l.modCount;
  308. size--;
  309. return result;
  310. }
  311. protected void removeRange(int fromIndex, int toIndex) {
  312. checkForComodification();
  313. //调用父类的removeRange方法
  314. l.removeRange(fromIndex+offset, toIndex+offset);
  315. this.modCount = l.modCount;
  316. size -= (toIndex-fromIndex);
  317. }
  318. public boolean addAll(Collection<? extends E> c) {
  319. return addAll(size, c);
  320. }
  321. public boolean addAll(int index, Collection<? extends E> c) {
  322. rangeCheckForAdd(index);
  323. int cSize = c.size();
  324. if (cSize==0)
  325. return false;
  326. checkForComodification();
  327. //在当前的子集合开始的位置进行插入
  328. l.addAll(offset+index, c);
  329. this.modCount = l.modCount;
  330. size += cSize;
  331. return true;
  332. }
  333. public Iterator<E> iterator() {
  334. return listIterator();
  335. }
  336. public ListIterator<E> listIterator(final int index) {
  337. checkForComodification();
  338. rangeCheckForAdd(index);
  339. //返回的是一个匿名内部类
  340. return new ListIterator<E>() {
  341. private final ListIterator<E> i = l.listIterator(index+offset);
  342. public boolean hasNext() {
  343. return nextIndex() < size;
  344. }
  345. public E next() {
  346. if (hasNext())
  347. return i.next();
  348. else
  349. throw new NoSuchElementException();
  350. }
  351. public boolean hasPrevious() {
  352. return previousIndex() >= 0;
  353. }
  354. public E previous() {
  355. if (hasPrevious())
  356. return i.previous();
  357. else
  358. throw new NoSuchElementException();
  359. }
  360. public int nextIndex() {
  361. return i.nextIndex() - offset;
  362. }
  363. public int previousIndex() {
  364. return i.previousIndex() - offset;
  365. }
  366. public void remove() {
  367. i.remove();
  368. SubList.this.modCount = l.modCount;
  369. size--;
  370. }
  371. public void set(E e) {
  372. i.set(e);
  373. }
  374. public void add(E e) {
  375. i.add(e);
  376. SubList.this.modCount = l.modCount;
  377. size++;
  378. }
  379. };
  380. }
  381. public List<E> subList(int fromIndex, int toIndex) {
  382. return new SubList<>(this, fromIndex, toIndex);
  383. }
  384. private void rangeCheck(int index) {
  385. if (index < 0 || index >= size)
  386. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  387. }
  388. private void rangeCheckForAdd(int index) {
  389. if (index < 0 || index > size)
  390. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  391. }
  392. private String outOfBoundsMsg(int index) {
  393. return "Index: "+index+", Size: "+size;
  394. }
  395. private void checkForComodification() {
  396. if (this.modCount != l.modCount)
  397. throw new ConcurrentModificationException();
  398. }
  399. }
  400. //相较于SubList内部类,多了一个是否可以随机访问的标志
  401. class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
  402. RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
  403. super(list, fromIndex, toIndex);
  404. }
  405. public List<E> subList(int fromIndex, int toIndex) {
  406. return new RandomAccessSubList<>(this, fromIndex, toIndex);
  407. }
  408. }

通过源码,我们可以发现,AbstractList的源码在结构上分为了两种内部迭代器,两种内部类以及AbstractList本身的代码,接下来,我们来分别解释在阅读源码中遇到的一些问题

索引和游标的关系

Java基础系列(四十二):集合之AbstractList - 图2这里我画了一个图,然后对照着这个图,我们再来看一下ListItr中的一些代码:

         //下一位的索引值等于光标值
        public int nextIndex() {
            return cursor;
        }

        //上一位的索引值等于光标值减一
        public int previousIndex() {
            //其实这里并不理解,为啥不去检查索引越界。。
            return cursor-1;
        }

假定迭代器现在运行到1所在的位置,可以很容易的看出当迭代器处于这个位置的时候,去调用nextIndex()方法得到的是1,而调用previousIndex得到的就是0。这是完全符合我们的逻辑的,接下来,我们再来看previous()方法的源码:

//获取上一位的元素,这里在后面会有画图帮助理解
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();
    }
}

其实这里我在分析的时候是存在疑问的(为什么这里的lastRet等于cursor,而Itr中的next()方法的实现中cursor实际上等于lastRet - 1),在画完图分析索引和游标的关系之后又来看一遍才恍然大悟,

这里的lastRet代表的是上一次迭代到的元素的光标位置,所以,我们来举个例子,当迭代器在4的位置的时候,使用了previous()方法,这时的迭代器的位置是在3,而上次迭代到的元素的游标位置也是3,而如果使用了next()方法,使用之后,迭代器的位置在5,而上一次迭代到的元素确是4。这也印证了nextIndex()previousIndex()的逻辑。

expectedModCount 和 modCount

从源码中我们可以看到

//这个变量是transient的,也就说序列化的时候是不需要储存的 
protected transient int modCount = 0;

这个变量代表着当前集合对象的结构性修改的次数,每次进行修改都会进行加1的操作,而expectedModCount代表的是迭代器对对象进行结构性修改的次数,这样的话每次进行结构性修改的时候都会将expectedModCountmodCount进行对比,如果相等的话,说明没有别的迭代器对对对象进行修改。如果不相等,说明发生了并发的操作,就会抛出一个异常。而有时也会不这样进行判断:

 //删除上一次迭代器越过的元素
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                   //调用需要子类去实现的remove方法
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                //每次删除后,将lastRet置为-1,防止连续的删除
                lastRet = -1;
                //将修改次数赋给迭代器对对象的结构修改次数这个会在下面进行详解
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                //如果出现索引越界,说明发生了并发的操作导致,所以抛出一个并发操作异常。
                throw new ConcurrentModificationException();
            }
        }

这里的设计在于,进行删除操作后,将修改次数和迭代器对象进行同步,虽然在方法的开始进行了checkForComodification()方法的判断,但是担心的是再进行删除操作的时候发生了并发的操作,所以在这里进行了try...catch...的处理,当发生了索引越界的异常的时候,说明一定是发生了并发的操作,所以抛出一个ConcurrentModificationException()

关于SubList和RandomAccessSubList

通过阅读源码我们可以知道,这个类实际上就是一个啃老族。基本上方法全是直接去加上offset后去调用的父类的方法,而RandomAccessSubList只是在此基础上实现了RandomAccess的接口,而这个接口是干嘛的呢?


package java.util;
/**
 * Marker interface used by <tt>List</tt> implementations to indicate that
 * they support fast (generally constant time) random access.  The primary
 * purpose of this interface is to allow generic algorithms to alter their
 * behavior to provide good performance when applied to either random or
 * sequential access lists.
 */
public interface RandomAccess {
}

通过阅读英文注释后我们可以知道,这个接口仅仅是一个标志性接口,用来标志是否可以随机访问的。

下节预告

接下来,我们终于要接触到第一个真正意义上的实现类了,敬请期待哟~


公众号

Java基础系列(四十二):集合之AbstractList - 图3