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 ...
随机推荐
- Java修炼——四种方式解析XML_DOM4J
四种方式解析XML:DOM JDOM DOM4J SAX 注意: DOM4J使用是需要上传jar包的. 先写一个XML栗子: <?xml version="1.0& ...
- [TimLinux] django WSGI入口分析及自定义WSGIHandler思路
1. 命令行启动 命令行是通过runserver子命令来启动的,对应的django模块为django.core.management.commands.runserver,调用关系结构: # 简化的运 ...
- DRF Django REST framework 之 路由器与版本控制组件(七)
路由器 一些Web框架提供了用于自动确定应如何将应用程序的URL映射到处理传入请求的逻辑的功能. 而DRF的路由器组件也提供了一种简单,快速且一致的方式将视图逻辑映射到一组URL上. 路由器组件的使用 ...
- 小白的springboot之路(十)、全局异常处理
0.前言 任何系统,我们不会傻傻的在每一个地方进行异常捕获和处理,整个系统一般我们会在一个的地方统一进行异常处理,spring boot全局异常处理很简单: 介绍前先说点题外话,我们现在开发系统,都是 ...
- JS-常考算法题解析
常考算法题解析 这一章节依托于上一章节的内容,毕竟了解了数据结构我们才能写出更好的算法. 对于大部分公司的面试来说,排序的内容已经足以应付了,由此为了更好的符合大众需求,排序的内容是最多的.当然如果你 ...
- 索引与Order By
Order By 将对结果进行排序,这里的排序最大的特点是资源密集型,尽管多数时候它同时也是CPU密集型的.数据库在进行排序时,必须缓冲临时结果,读取到所有输入,并在完整的排序操作后才能产生第一个输出 ...
- 搞清楚Spring Cloud架构原理的这4个点,轻松应对面试
前言 现在分布式系统基本上都是标配了,如果你现在还在玩儿单机,没有接触过这些东西的话,权当是为你打开一扇新的大门吧. 大的单体项目 以前我们做单机系统的时候,所有的代码都在一个项目里面,只是不同的模块 ...
- windows系统下sublime text3开发工具前端配置
1.打开https://www.sublimetext.com/3下载最新版Sublime Text 3安装. 2.打开packagecontrol安装方法按提示安装packagecontrol,或者 ...
- nginx代理grafana
希望通过Nginx为服务器上的grafana进行代理,实现通过在当前域名后加/grafana在公网进行访问,开始按照百度的方法弄了几个小时都不行,后面仔细看了官方的文档才弄好,Mark一下. Ngin ...
- 集群环境下,你不得不注意的ASP.NET Core Data Protection 机制
引言 最近线上环境遇到一个问题,就是ASP.NET Core Web应用在单个容器使用正常,扩展多个容器无法访问的问题.查看容器日志,发现以下异常: System.Security.Cryptogra ...