在使用foreach 与 Iterator 时不能有数据的修改以及循环内部累加器

2024-01-09 11:20

本文主要是介绍在使用foreach 与 Iterator 时不能有数据的修改以及循环内部累加器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

foreach 与 Iterator java中自遍历不能有累加器

我们知道,在Java中使用foreach对集和进行遍历时,是无法对该集和进行插入、删除等操作,比如以下代码:

    for(Person p : personList){        if(StringUtil.isBlank(p.getName())){            personList.remove(p);       }   }

执行代码,报以下异常:

   Exception in thread "main" java.util.ConcurrentModificationException   at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)   at java.util.ArrayList$Itr.next(ArrayList.java:859)   at com.xiuhao.service.ForeachDemo.main(ForeachDemo.java:20)

根据错误提示,定位ArrayList的源码,找到以下内容:

   
 /*** An optimized version of AbstractList.Itr*/private class Itr implements Iterator<E> {int cursor;       // index of next element to returnint lastRet = -1; // index of last element returned; -1 if no suchint expectedModCount = modCount;Itr() {}public boolean hasNext() {return cursor != size;}@SuppressWarnings("unchecked")public E next() {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() {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {ArrayList.this.remove(lastRet);cursor = lastRet;lastRet = -1;expectedModCount = modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}
​...
​final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}}

即foreach的实现过程中使用Iterator的next()方法来实现遍历。在每次调用该方法前,首先执行checkForComodification()方法检查modCountexpectedModCount的值是否相等,如果不相等则直接抛出上文中的 ConcurrentModificationException

再来查看modCountexpectedModCount的值是如何定义的,在代码的开头部分初始化expectedModCount = modCount,即两者的值是相等的。modCountArrayList父类AbstractArrayList的成员变量,其定义如下:

 /*** The number of times this list has been <i>structurally modified</i>.* 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.** <p>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* <i>fail-fast</i> behavior, rather than non-deterministic behavior in* the face of concurrent modification during iteration.** <p><b>Use of this field by subclasses is optional.</b> 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;

由此可见,modCount纪录了有改变list大小等结构性变化或者其他使得遍历过程中产生不正确的结果的其它方式的次数,它的初始值为0,当每次迭代器被调用时,其值会被初始化成该list的大小。

当执行到personList.remove(p);时,查看remove()方法的源码:

   
 /*** Removes the element at the specified position in this list.* Shifts any subsequent elements to the left (subtracts one from their* indices).** @param index the index of the element to be removed* @return the element that was removed from the list* @throws IndexOutOfBoundsException {@inheritDoc}*/public E remove(int index) {rangeCheck(index);
​modCount++;E oldValue = elementData(index);
​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
​return oldValue;}

发现该方法执行modCount++;,改变了值大小,当迭代器再次执行next()方法并调用checkForComodification()时,由于expectedModCount的值没有改变,因此会抛出 ConcurrentModificationException异常。同理,list的add方法同样会出发modCount++;,因此,无法使用foreach循环对list进行添加删除等操作。

那么,如何通过遍历进行list的增删操作呢,再次回到Iterator的源代码:

  
  public void remove() {if (lastRet < 0)throw new IllegalStateException();checkForComodification();
​try {ArrayList.this.remove(lastRet);cursor = lastRet;lastRet = -1;expectedModCount = modCount; //重新设置expectedModCount} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}

注意到Iteratorremove()方法重新设置了expectedModCount = modCount;,因此当再次执行next()时保证了两个参数一直相同,不会抛出异常,代码如下:

    
Iterator<Person> iterator =  personList.iterator();while (iterator.hasNext()) {if(StringUtil.isBlank(iterator.next().getName())){iterator.remove();}}

此外,对集和进行遍历编辑的方法包括:

  • 直接使用普通for循环进行操作

    
int size = personList.size();for(int i=0; i<size ;i++){if(StringUtil.isBlank(personList.get(i).getName())){personList.remove(i);}}
  • 使用Java 8中提供的filter过滤

List<Person> persons = personList.stream().filter(persron -> StringUtil.isNotBlank(persron.getName())).collect(Collectors.toList());

这篇关于在使用foreach 与 Iterator 时不能有数据的修改以及循环内部累加器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/586951

相关文章

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

Java Optional的使用技巧与最佳实践

《JavaOptional的使用技巧与最佳实践》在Java中,Optional是用于优雅处理null的容器类,其核心目标是显式提醒开发者处理空值场景,避免NullPointerExce... 目录一、Optional 的核心用途二、使用技巧与最佳实践三、常见误区与反模式四、替代方案与扩展五、总结在 Java

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Qt中QUndoView控件的具体使用

《Qt中QUndoView控件的具体使用》QUndoView是Qt框架中用于可视化显示QUndoStack内容的控件,本文主要介绍了Qt中QUndoView控件的具体使用,具有一定的参考价值,感兴趣的... 目录引言一、QUndoView 的用途二、工作原理三、 如何与 QUnDOStack 配合使用四、自

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

Spring Boot循环依赖原理、解决方案与最佳实践(全解析)

《SpringBoot循环依赖原理、解决方案与最佳实践(全解析)》循环依赖指两个或多个Bean相互直接或间接引用,形成闭环依赖关系,:本文主要介绍SpringBoot循环依赖原理、解决方案与最... 目录一、循环依赖的本质与危害1.1 什么是循环依赖?1.2 核心危害二、Spring的三级缓存机制2.1 三

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t