使用迭代器遍历集合出现ConcurrentModificationException的总结

思路

1.首先创建集合

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

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

public class Test {
	public static void main(String[] args) {
	    //创建集合对象
	    ArrayList<String> al = new ArrayList<String>();
	    //添加元素
	    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<String> al = new ArrayList<String>();
		al.add("hello");
		al.add("world");
		al.add("java");
		//ListIterator是Iterator的扩展
		ListIterator<String> 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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值