Java_foreach不能remove
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的更多相关文章
- EntityFramework Core 1.1 Add、Attach、Update、Remove方法如何高效使用详解
前言 我比较喜欢安静,大概和我喜欢研究和琢磨技术原因相关吧,刚好到了元旦节,这几天可以好好学习下EF Core,同时在项目当中用到EF Core,借此机会给予比较深入的理解,这里我们只讲解和EF 6. ...
- [LeetCode] Remove K Digits 去掉K位数字
Given a non-negative integer num represented as a string, remove k digits from the number so that th ...
- [LeetCode] Remove Duplicate Letters 移除重复字母
Given a string which contains only lowercase letters, remove duplicate letters so that every letter ...
- [LeetCode] Remove Invalid Parentheses 移除非法括号
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...
- [LeetCode] Remove Linked List Elements 移除链表元素
Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 -- ...
- [LeetCode] Remove Duplicates from Sorted List 移除有序链表中的重复项
Given a sorted linked list, delete all duplicates such that each element appear only once. For examp ...
- [LeetCode] Remove Duplicates from Sorted List II 移除有序链表中的重复项之二
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb ...
- [LeetCode] Remove Duplicates from Sorted Array II 有序数组中去除重复项之二
Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For exampl ...
- [LeetCode] Remove Element 移除元素
Given an array and a value, remove all instances of that value in place and return the new length. T ...
随机推荐
- [TimLinux] Python 再谈元类 metaclass
本博文通过对以下链接进行理解后,编写. https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python 1. 类 类 ...
- [TimLinux] django model关于QuerySet
1. 获取执行过的sql命令 from django.db import connections connections['default'].queries 2. 获取QuerySet将执行的sql ...
- 2018 牛客国庆集训派对Day4 - H 树链博弈
链接:https://ac.nowcoder.com/acm/contest/204/H来源:牛客网 题目描述 给定一棵 n 个点的树,其中 1 号结点是根,每个结点要么是黑色要么是白色 现在小 Bo ...
- 探究 Nginx 中 reload 流程的真相
今天这篇文章主要来介绍下 Nginx 的 reload 流程.实际上在之前文章中,在更改了 nginx 配置文件时,我们都会执行 nginx -s reload 命令,我们执行这条命令的原因是希望 n ...
- Mybatis获取自动增长Id
Mybatis获取自动增长Id MyBatis成功插入后获取自动增长的id 1.向xxMapping.xml配置中加上两个配置. <insert id="insertUser" ...
- CentOS 7.4搭建LAMP,LAMP:Linux、Apache、MySQL、PHP
CentOS 7.4搭建LAMP,LAMP:Linux.Apache.MySQL.PHP. 目录: 第一部分 准备工作 第二部分 安装Apache服务 第三部分 安装MySQL服务 第四部分 搭建PH ...
- 【Eureka】集群搭建
[Eureka]集群搭建 转载============================================== ====================================== ...
- 如何上传项目到github
喜欢的同学可以看一下原文,讲得更加详细哦 原文地址:http://www.cnblogs.com/cxk1995/p/5800196.html 首先你需要一个github账号,所有还没有的话先去注册吧 ...
- netcore 创建腾讯云私有镜像 发布到docker 实战
上一篇博客写的 netcoer上传到docker ,编译 并发布,传送门:FineUICore基础版部署到docker实战 这是一种笨方法,理想的方法是,在本地编译成镜像,然后推送到镜像仓库,服务器的 ...
- git项目创建及在idea工具中使用
1.安装git管理工具 2.在自己github账号上创建一个项目仓库,比如我创建的是renrenView 网页翻译如下: 参数解析如下: 3.本地项目同步到远程仓库步骤 在本地初始化git项目 git ...