最后
前端CSS面试题文档,JavaScript面试题文档,Vue面试题文档,大厂面试题文档
开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】
1.ArrayList集合对象调用remove方法删除lastRet索引位置元素。则此时集合对象底层数组改变为
2.cursor移动到lastRet指向位置,lastRet被重置指向-1
综上所诉:指针用于获取集合元素,游标用于探测指针将要指向的下一个元素是否存在
modCount, fail-fast 快速失败机制
在介绍ArrayList特性时,我们走读add和remove(包括clear)方法时,发现ArrayList集合在插入元素和删除(清空)元素时,都会操作modCount变量
而modCount变量是定义在抽象类AbstractList中的。AbstractList类是作为List接口实现类的父类或超类,是List接口实现类的模板。
该变量被修饰为protected,很明显是给子类使用的。
该变量的介绍是:
The number of times this list has been structurally modified.
【list被结构化修改的次数。】
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.
【结构化修改是指:在迭代list过程中,改变了list的size属性值,或者其他方式扰乱了该值,则可能会导致迭代出现不正确的结果。】【注意:list集合什么样的操作会影响list的size属性?size属性是指list集合元素的个数,一般add,remove,clear,retainAll等改变集合元素个数的操作会影响,而set,get,trimToSize,foreach等操作不会】
This field is used by the iterator and list iterator implementation returned by the {@code iterator} and {@code listIterator} methods.
【 modCount被用在(由iterator()方法和listIterator()返回的)Iterator迭代器和ListIterator迭代器实现类中】【前面说了使list的size改变的操作,都会导致modCount值发生变化。而modCount最终用来干嘛呢?这里说了是用在迭代器中】
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.
【如果modCount被意外改变,迭代器将会抛出 ConcurrentModificationException的异常给next,remove,previous,set,add 这些操作。】【这里说,在迭代过程中,如果modCount值变化了,那么迭代器对象调用next,remove,previous,set,add等操作时,都会抛并发修改异常】
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中
性能优化
1.webpack打包文件体积过大?(最终打包为一个js文件)
2.如何优化webpack构建的性能
3.移动端的性能优化
4.Vue的SPA 如何优化加载速度
5.移动端300ms延迟
6.页面的重构
所有的知识点都有详细的解答,我整理成了280页PDF《前端校招面试真题精编解析》。
开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】
0、导致ArrayList集合结构化修改的操作有哪些?
集合结构化修改,即改变了集合的modCount值。
ArrayList中
性能优化
1.webpack打包文件体积过大?(最终打包为一个js文件)
2.如何优化webpack构建的性能
3.移动端的性能优化
4.Vue的SPA 如何优化加载速度
5.移动端300ms延迟
6.页面的重构
所有的知识点都有详细的解答,我整理成了280页PDF《前端校招面试真题精编解析》。
开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】