foreach

阿里巴巴java开发手册

【强制】不要在foreach循环里进行元素的remove/add操作。remove元素请使用Iterator方式,如果并发操作,需要对Iterator对象加锁。

反例
List<String> a = new ArrayList<String>();
a.add("1");
a.add("2");
for (String temp : a) {
if("1".equals(temp)){
a.remove(temp);
}
}
正例
Iterator<String> it= a.iterator();
while(it.hasNext()){
String temp = it.next();
if(删除元素的条件){
it.remove();
}
}

foreach源码

foreach遍历集合,其实是走的Iterator,首先判断hasNext(),如果没有了则终止循环,否则next()获取元素时,next()时,都要check一下集合元素个数是否变化了,如果变化了,则抛出异常。

Itr是ArrayList的内部类,实现了Iterator接口

private class Itr implements Iterator<E> {

 int cursor;       // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount; public boolean hasNext() {
return cursor != size;//游标不等于元素个数就是还有下一个
} public E next() {
checkForComodification();//check是否并发修改
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];
} final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

modCount是集合添加元素、删除元素的次数,expectedModCount是预期的修改次数。增删操作会使得modCount+1,不等于expetedModCount,所以抛出异常。

没有使用list.iterator时调用的是ArrayList自己的remove,并不会同步这两个值,导致抛出异常。调用了ArrayList.iterator之后,然后了Itr对象,此后再remove,remove方法中有让这两个值相等的操作。

迭代器方式移除

那为什么Iterator不会异常呢?

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

迭代器的remove方法会修改expectedModCount,从而使modCount与之相等

参考:https://blog.csdn.net/wangjun5159/article/details/61415358

Java_foreach不能remove的更多相关文章

  1. EntityFramework Core 1.1 Add、Attach、Update、Remove方法如何高效使用详解

    前言 我比较喜欢安静,大概和我喜欢研究和琢磨技术原因相关吧,刚好到了元旦节,这几天可以好好学习下EF Core,同时在项目当中用到EF Core,借此机会给予比较深入的理解,这里我们只讲解和EF 6. ...

  2. [LeetCode] Remove K Digits 去掉K位数字

    Given a non-negative integer num represented as a string, remove k digits from the number so that th ...

  3. [LeetCode] Remove Duplicate Letters 移除重复字母

    Given a string which contains only lowercase letters, remove duplicate letters so that every letter ...

  4. [LeetCode] Remove Invalid Parentheses 移除非法括号

    Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...

  5. [LeetCode] Remove Linked List Elements 移除链表元素

    Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 -- ...

  6. [LeetCode] Remove Duplicates from Sorted List 移除有序链表中的重复项

    Given a sorted linked list, delete all duplicates such that each element appear only once. For examp ...

  7. [LeetCode] Remove Duplicates from Sorted List II 移除有序链表中的重复项之二

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb ...

  8. [LeetCode] Remove Duplicates from Sorted Array II 有序数组中去除重复项之二

    Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For exampl ...

  9. [LeetCode] Remove Element 移除元素

    Given an array and a value, remove all instances of that value in place and return the new length. T ...

随机推荐

  1. Light oj 1140 How Many Zeroes?

    Jimmy writes down the decimal representations of all natural numbers between and including m and n, ...

  2. Orleans的入门教程

    Orleans的入门教程  官方Hello World 地址 https://github.com/dotnet/orleans/tree/master/Samples/2.0/HelloWorld ...

  3. 【HTTP】402- 深入理解http2.0协议,看这篇就够了!

    本文字数:3825字 预计阅读时间:20分钟 导读 http2.0是一种安全高效的下一代http传输协议.安全是因为http2.0建立在https协议的基础上,高效是因为它是通过二进制分帧来进行数据传 ...

  4. 【JS】313- 复习 回流和重绘

    点击上方"前端自习课"关注,学习起来~ 原文地址:我不是陈纪庚 segmentfault.com/a/1190000017329980 回流和重绘可以说是每一个web开发者都经常听 ...

  5. CCF-CSP题解 201712-3 Crontab

    做完一定要仔仔细细地看一遍题目再交,之后发现坑点只能追悔莫及.比如这次"英文缩写(不区分大小写)"\(OwQ\). 给定多个周期性执行的任务,每个任务调度执行有时间的要求.求给定时 ...

  6. 红帽杯-MISC-Advertising for Marriage

    convert -flip screenshot.png screensho1.png 本篇结合我上一博客https://www.cnblogs.com/qq3285862072/p/11869403 ...

  7. 全平台轻量开源verilog仿真工具iverilog+GTKWave使用教程

    前言 如果你只是想检查Verilog文件的语法是否有错误,然后进行一些基本的时序仿真,那么Icarus Verilog 就是一个不错的选择.相比于各大FPGA厂商的IDE几个G的大小,Icarus V ...

  8. vue中子组件直接修改父组件prop属性bug

    在有些时候,子组件直接修改父组件传来的 prop 对象的属性会出现不同步的问题. 比如,父组件传过来的一个对象 checkBoxObj: checkBoxObj:{ checked: false } ...

  9. 去掉 Idea 中注入 Mapper 警告的方法

    使用 Idea 的时候,自动装配 Mybatis 的 mapper.会一直出现红色波浪线的警告.看着难受.下面提供几种方式 方式一 为 @Autowired 注解设置required = false ...

  10. Intel和AMD的CPU性能对比图

    Intel和AMD的CPU性能对比图: