赞
踩
platformList.remove(platform);
modCount的值就被修改成了4。
所以在第2次获取元素时,modCount和expectedModCount的值就不相等了,所以抛出了java.util.ConcurrentModificationException异常。
既然不能使用foreach来实现,那么我们该如何实现呢?
主要有以下3种方法:
使用Iterator的remove()方法
使用for循环正序遍历
使用for循环倒序遍历
接下来一一讲解。
#2. 使用Iterator的remove()方法
使用Iterator的remove()方法的实现方式如下所示:
public static void main(String[] args) {
List platformList = new ArrayList<>();
platformList.add(“博客园”);
platformList.add(“CSDN”);
platformList.add(“掘金”);
Iterator iterator = platformList.iterator();
while (iterator.hasNext()) {
String platform = iterator.next();
if (platform.equals(“博客园”))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。