List集合之ArrayList(二)通过源码看迭代器实现,2024年最新前端大厂面试笔试题分享

This provides fail-fast behavior, rather than non-deterministic behavior in the face of concurrent modification during iteration.

【在迭代过程中,如果发现Concurrent modification并发修改情况时,迭代器会提供快速失败机制,而不是不知所措。】【这里吹了一下迭代器的快速失败机制很牛逼】

Use of this field by subclasses is optional.

【子类可以选择性的使用AbstractList抽象类中这个字段】【这里说了AbstractList的子类不一定需要使用modCount】

If a subclass wishes to provide fail-fast iterators (and list iterators), then it merely has to increment this field in its {@code add(int, E)} and {@code remove(int)} methods (and any other methods that it overrides that result in structural modifications to the list).

【如果子类希望提供支持快速失败机制的迭代器,它只需要在add(int, E),remove(int)方法(或者其他它的会导致结构化修改这个列表的方法)中增加modCount。】【这里说,如果AbstractList的子类使用modCount的话,每次导致list结构化修改的操作需要增加modCount】

A single call to {@code add(int, E)} or {@code remove(int)} must add no more than one to this field, or the iterators (and list iterators) will throw bogus {@code ConcurrentModificationExceptions}.

【只调用一次add或者remove,必须增加modCount,但是增加的值不能超过1。否则迭代器会抛出ConcurrentModificationException。】【这里说了每次结构化修改操作发生后,modCount最好只加1,如果加2,加3的话,迭代器就会抛出并发修改异常】

If an implementation does not wish to provide fail-fast iterators, this field may be ignored.

【如果实现类不希望提供支持快速失败机制的迭代器,则可以忽略modCount字段】【这里说明了modCount就是专门给迭代器用来判断是否快速失败的,如果不需要快速失败的话,可以忽略modCount】

/**

  • The number of times this list has been structurally modified.

  • Structural modifications are those that change the size of the

  • list, or otherwise perturb it in such a fashion that iterations in

  • progress may yield incorrect results.

  • This field is used by the iterator and list iterator implementation

  • returned by the {@code iterator} and {@code listIterator} methods.

  • If the value of this field changes unexpectedly, the iterator (or list

  • iterator) will throw a {@code ConcurrentModificationException} in

  • response to the {@code next}, {@code remove}, {@code previous},

  • {@code set} or {@code add} operations. This provides

  • fail-fast behavior, rather than non-deterministic behavior in

  • the face of concurrent modification during iteration.

  • Use of this field by subclasses is optional. If a subclass

  • wishes to provide fail-fast iterators (and list iterators), then it

  • merely has to increment this field in its {@code add(int, E)} and

  • {@code remove(int)} methods (and any other methods that it overrides

  • that result in structural modifications to the list). A single call to

  • {@code add(int, E)} or {@code remove(int)} must add no more than

  • one to this field, or the iterators (and list iterators) will throw

  • bogus {@code ConcurrentModificationExceptions}. If an implementation

  • does not wish to provide fail-fast iterators, this field may be

  • ignored.

*/

protected transient int modCount = 0;

ArrayList迭代器源码分析

================

public Iterator iterator()


/**

  • Returns an iterator over the elements in this list in proper sequence.

  • The returned iterator is fail-fast.

  • @return an iterator over the elements in this list in proper sequence

*/

public Iterator iterator() {

return new Itr();// Itr类是Iterator接口的实现类,同时是定义在ArrayList中的私有成员内部类。

}

/**

  • An optimized version of AbstractList.Itr

*/

private class Itr implements Iterator {

int cursor; // index of next element to return // 游标,初始值cursor=0,即游标处在集合第一个元素上,游标用于探测下一个元素

int lastRet = -1; // index of last element returned; -1 if no such // 指针,初始值lastRet=-1,即指针初始时不指向集合元素,指针用于获取集合元素

int expectedModCount = modCount;// modCount是指集合被结构化修改的次数。这里在迭代器对象被创建时备份了当前集合的modCount值到exceptedModCount。这是为了保证迭代器迭代过程中,实时监测集合的modCount值是否被改变了,即exceptedModCount!= modCount,如果是,则集合元素已经被结构化修改,迭代器就会抛出并发修改异常。

Itr() {} // 只提供了无参构造器

public boolean hasNext() {// hasNext方法用于判断迭代器将要迭代的下一个元素是否存在

return cursor != size;// 由于集合元素是0~size-1的,而迭代器的迭代又是顺序执行的,即只会按0,1,2,3,…,size-1的迭代顺序迭代,所以当游标cursor位置最多移动到size位,然后返回false,表示没有下一个元素了。

}

@SuppressWarnings(“unchecked”)

public E next() {// next方法用于获取下一个元素,但是内部操作比较复杂

checkForComodification();// 执行next操作前,检查集合没有被结构化修改,即保证exceptedModCount == modCount成立,若成立则继续执行,否则抛出并发修改异常

int i = cursor;

if (i >= size) // 如果游标已经在集合size位置,或者超出size位置

throw new NoSuchElementException();// 则next方法必然无法获得下一个元素,即无下一个元素存在

Object[] elementData = ArrayList.this.elementData;

if (i >= elementData.length) // 如果游标位置已经超出了集合容量(这种情况应该是cursor已经在size位置,但是此时对集合进行了trimToSize操作,则集合底层数组容量就是size,就会出现i>=elementData.length,但是此时游标cursor其实已经超出了elementData数组的索引范围,此处java视为并发修改异常)

throw new ConcurrentModificationException();

cursor = i + 1;// 如果上面都没有问题的话,则游标先移动到下一位

return (E) elementData[lastRet = i];// 然后指针lastRet指向游标当前所在位置的前一位,并获取该位置的元素,返回。

}

public void remove() {// remove方法用于删除迭代器正在迭代的元素,内部实现比较复杂

if (lastRet < 0) // 首先迭代器正在迭代的元素,就是指针lastRet指向的元素,当迭代器初始化时,此时指针不指向集合中任何元素,即lastRet是-1时,就会由于没有迭代的元素,所以不能remove空的元素,就会报错非法状态异常

throw new IllegalStateException();

checkForComodification();// remove操作前要检查集合是否被结构化修改

try {

ArrayList.this.remove(lastRet);// 先利用集合对象删除lastRet指向的元素,注意此时集合的modCount值会被改变

cursor = lastRet; // 由于指针lastRet指向的元素已经被删除了,所以理论上指针当前无指向元素,而由于cursor指向的元素后移了一位,所以cursor指向了lastRet原本的位置

lastRet = -1; // 由于lastRet指向的元素已经被删除了,所以lastRet无指向元素,所以将其重置位-1

expectedModCount = modCount;// 由于之前集合的remove操作已经改变了集合的modCount值,所以将集合最新的modCount值给了excepetedModCount

} catch (IndexOutOfBoundsException ex) {

throw new ConcurrentModificationException();// try里面能抛出异常的只有集合的remove操作,如果该步抛异常了,说明要remove的元素出问题了,则报错并发修改异常

}

}

@Override

@SuppressWarnings(“unchecked”)

public void forEachRemaining(Consumer<? super E> consumer) {// foreachRemaining方法用于遍历集合每个元素给consumer处理,外部调用此方法,需要提供Consumer接口的实现类对象,由于Consumer是函数式接口,所以建议Lambda表达式,直接重写accept方法即可,accepet的方法形参就是foreachRemaining方法遍历的每个集合元素

Objects.requireNonNull(consumer);// 首先保证consumer非null,否则后面调用consumer的accept操作会报错空指针

final int size = ArrayList.this.size;// 获取集合元素个数

int i = cursor;//

if (i >= size) {// 如果游标指向已经超出的集合元素的范围,则方法结束,即顺序迭代已经迭代到了最后一个元素

return;

}

final Object[] elementData = ArrayList.this.elementData;

if (i >= elementData.length) {//同next方法中该逻辑解释

throw new ConcurrentModificationException();

}

while (i != size && modCount == expectedModCount) {// 只要没有遍历结束且集合没有被结构化修改,就一直执行

consumer.accept((E) elementData[i++]);// 利用consumer的accept方法处理集合元素

}

// update once at end of iteration to reduce heap write traffic

cursor = i;// 当上面遍历结束后,i已经等于size了,即游标指向了size位置

lastRet = i - 1;//而指针此时指向游标前一位,即集合最后一个元素的位置

checkForComodification();// 在foreachRemaining结束前,判断有无并发修改异常,若没有,则正常结束方法,若有则抛出异常,但是此时集合元素已经被遍历处理完成。

}

final void checkForComodification() {

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

}

}

源码走读分析加注释在上面代码每行后面。但是过于抽象,下面通过画图的方式,演示Itr类的hasNext,next,remove,foreachRemaining方法执行过程

下图是关于hasNext()和next()

下图是关于remove()


下图是关于foreachRemaining(Consumer consumer)

public ListIterator listIterator(int index)


/**

  • Returns a list iterator over the elements in this list (in proper

  • sequence), starting at the specified position in the list.

  • The specified index indicates the first element that would be

  • returned by an initial call to {@link ListIterator#next next}.

  • An initial call to {@link ListIterator#previous previous} would

  • return the element with the specified index minus one.

  • The returned list iterator is fail-fast.

  • @throws IndexOutOfBoundsException {@inheritDoc}

*/

public ListIterator listIterator(int index) {

if (index < 0 || index > size)

throw new IndexOutOfBoundsException("Index: "+index);

return new ListItr(index);

}

public ListIterator listIterator()


/**

  • Returns a list iterator over the elements in this list (in proper

  • sequence).

  • The returned list iterator is fail-fast.

  • @see #listIterator(int)

*/

public ListIterator listIterator() {

return new ListItr(0);

}

从上面两个方法定义可以看出

listIterator()返回的是new ListItr(0)

listIterator(int index)返回的是 new ListItr(index)

说明ListItr实现类必须传入一个ArrayList对象某个元素的索引值。至于该索引值的作用,需要看ListItr类如何使用它。

ListItr实现类定义

/**

  • An optimized version of AbstractList.ListItr

*/

private class ListItr extends Itr implements ListIterator {

ListItr(int index) {

super();

cursor = index;

}

public boolean hasPrevious() {

return cursor != 0;// 可以和hasNext对比

}

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();

}

}

}

从ListItr类定义来看,index会被赋值给cursor。

对比之前的Itr类,Itr类的cursor初始是0,后续随着next()方法或foreachRemainingf方法的调用而改变,即没有其他方式可以cursor值。

而ListItr中,将cursor的初始值交给了外部调用者。即调用者希望迭代器的游标(下一个元素)指向哪里就指向哪里。

ListItr中的

nextIndex()方法就是获取cursor值

previousIndex()方法就是获取cursor-1值

hasPrevious()方法和hasNext()相反,hasNext()是保证游标指向不超出集合元素尾部索引,hasPrevious()是保证游标指向不超出集合元素头部索引

previous()和next()实现刚好相反,next()是将cursor,lastRet不断向后移动,previous()是将cursor,lastRet不断向前移动

set(E e)是修改lastRet指向的元素为e

add(E e)是在cursor位置添加新的元素,且将lastRet重置为-1

ListIterator接口定义

package java.util;

public interface ListIterator extends Iterator {

boolean hasNext();

E next();

boolean hasPrevious();

E previous();

int nextIndex();

int previousIndex();

void remove();

void set(E e);

void add(E e);

}

可以发现ListIterator接口继承了Iterator接口,即ListIterator接口也有hasNext(),next(),remove(),foreachRemaining(Consumer consumer)方法。

同时ListIterator还额外增加了hasPrevious(),previous(),nextIndex(),perviousIndex(),set(E e),add(E e)

其实新增的方法依据ArrayList特性定制的。

由于ArrayList的底层是数组,所以ArrayList的元素可以支持随机访问,而Iterator中只支持hasNext(),next()访问下一个元素,不支持访问上一个元素。

所以在ListIterator中,根据ArrayList元素访问的随机性特点,增加了hasPrevious(),previous()访问上一个元素的操作。

另外ArrayList也支持修改任意索引位置的元素,以及增加一个元素,获取元素索引等操作。即定制了nextIndex(),perviousIndex(),set(E e),add(E e)等方法。

图示示hasPrevious(),previous(),add(E e),set(E e)的过程

思考题

===

0、导致ArrayList集合结构化修改的操作有哪些?


集合结构化修改,即改变了集合的modCount值。

ArrayList中

add(E e)

add(int index, E e)

addAll(Collection c)

addAll(int index, Collection c)

remove(E e)

remove(int index)

removeAll(Collecion c)

removeIf(Predicate p)

retainAll(Collection c)

trimToSize()

ensureCapacity(int minCapacity)

replaceAll(UnaryOperator uo)

sort(Comparator cn)

总结上面这些操作:

增加,删除元素 这些改变了集合size的操作(包括所有的add,remove以及retainAll)

改变集合容量的操作 (trimToSize,ensureCapacity)

超过一个的改变集合元素(replaceAll,sort)

这些将集合改的面目全非的操作都可以看成结构化修改

1、请看下面代码运行结果


import java.util.ArrayList;

import java.util.Collections;

import java.util.ListIterator;

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数前端工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip1024c (备注前端)
img

打开全栈工匠技能包-1小时轻松掌握SSR

两小时精通jq+bs插件开发

生产环境下如歌部署Node.js

CodeChina开源项目:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

网易内部VUE自定义插件库NPM集成

谁说前端不用懂安全,XSS跨站脚本的危害

webpack的loader到底是什么样的?两小时带你写一个自己loader

一个人可以走的很快,但一群人才能走的更远。如果你从事以下工作或对以下感兴趣,欢迎戳这里加入程序员的圈子,让我们一起学习成长!

AI人工智能、Android移动开发、AIGC大模型、C C#、Go语言、Java、Linux运维、云计算、MySQL、PMP、网络安全、Python爬虫、UE5、UI设计、Unity3D、Web前端开发、产品经理、车载开发、大数据、鸿蒙、计算机网络、嵌入式物联网、软件测试、数据结构与算法、音视频开发、Flutter、IOS开发、PHP开发、.NET、安卓逆向、云计算

84MC92Mi1kN2M3ZWVjOWJiZGVmYjJiMjNjNzExNzgzZWM4MzIwZV9oZC5qcGc?x-oss-process=image/format,png)

谁说前端不用懂安全,XSS跨站脚本的危害

webpack的loader到底是什么样的?两小时带你写一个自己loader

一个人可以走的很快,但一群人才能走的更远。如果你从事以下工作或对以下感兴趣,欢迎戳这里加入程序员的圈子,让我们一起学习成长!

AI人工智能、Android移动开发、AIGC大模型、C C#、Go语言、Java、Linux运维、云计算、MySQL、PMP、网络安全、Python爬虫、UE5、UI设计、Unity3D、Web前端开发、产品经理、车载开发、大数据、鸿蒙、计算机网络、嵌入式物联网、软件测试、数据结构与算法、音视频开发、Flutter、IOS开发、PHP开发、.NET、安卓逆向、云计算

  • 30
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值