博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用迭代器遍历集合出现ConcurrentModificationException的总结
阅读量:6893 次
发布时间:2019-06-27

本文共 1322 字,大约阅读时间需要 4 分钟。

思路

1.首先创建集合

2.使用集合对象添加元素

3.创建Iterator对象,并进行循环遍历

public class Test {	public static void main(String[] args) {	    //创建集合对象	    ArrayList
al = new ArrayList
(); //添加元素 al.add("hello"); al.add("world"); al.add("java"); //创建Iterator对象 Iterator it = al.iterator(); while(it.hasNext()){ //判断集合中是否会有下一个元素 String str = (String) it.next(); //在此添加一个添加,如果输出到了"world"就再为集合添加"sql"元素 if("world".equals(str)){ al.add("sql"); } } System.out.println(al); }}复制代码

这时你会发现程序会出现ConcurrentModificationException异常

通过定位错误的位置,可以知道是String str = (String) it.next();的错误。

可以通过查看iterator的源码得知是因为当前的数量和预期的数量不一致导致的错误

错误的原因:在使用iterator遍历集合时,我们又使用ArrayList对象向集合中添加元素造成的。

解决方式:通过使用ListIterator接口的迭代器解决

public class Test {	public static void main(String[] args) {		ArrayList
al = new ArrayList
(); al.add("hello"); al.add("world"); al.add("java"); //ListIterator是Iterator的扩展 ListIterator
li = al.listIterator(); while(li.hasNext()){ String str = li.next(); if("world".equals(str)){ li.add("sql"); } } System.out.println(al); }}复制代码

这里需要注意add()方法要使用ListIterator的迭代器对象进行添加

这样问题就完美的解决了

转载于:https://juejin.im/post/5c4d308de51d45090d307a80

你可能感兴趣的文章
Tomcat 生产服务器性能优化
查看>>
ubuntu下Odoo10开发环境配置
查看>>
Java ServletContext 详解
查看>>
html <area> 的用法,图片热点的使用
查看>>
CheckBox的CheckedChanged事件获取DataGrid选中行的值
查看>>
linux exec 文件重定向
查看>>
jquery mobile——必须引入的文件及头信息
查看>>
Redis安装部署
查看>>
redis-sentinel 做HA
查看>>
图为先C++笔试20131017
查看>>
模仿墨迹天气-demo
查看>>
mysql基于日志点的复制步骤
查看>>
查看centos中的用户和用户组
查看>>
Elixir ABC 1
查看>>
ZeroSpeech
查看>>
Fiddler 调试手机应用
查看>>
常用的正则表达式
查看>>
Jstl 中<c:if test="${value=='0'}"> 不能做判断??
查看>>
python matplotlib及sklearn安装
查看>>
困惑2017?
查看>>