在Java中,当使用for-each
循环(也称为增强型for
循环)遍历集合时,通常不会抛出ConcurrentModificationException
异常。这是因为for-each
循环在内部使用了迭代器来遍历集合,而迭代器在遍历过程中会检查底层集合是否发生了意外的修改。
Iterator
接口提供了hasNext()
、next()
和remove()
等方法。for-each
循环不会抛出并发修改异常for-each
循环在内部使用了迭代器来遍历集合。例如,对于ArrayList
,for-each
循环实际上使用了ArrayList
的Iterator
。for-each
循环在内部使用了迭代器来遍历集合。例如,对于ArrayList
,for-each
循环实际上使用了ArrayList
的Iterator
。ArrayList
、HashMap
等)都实现了快速失败机制。这意味着如果在迭代过程中检测到集合被修改,就会抛出ConcurrentModificationException
。但是,for-each
循环通过迭代器进行遍历,迭代器在每次调用next()
方法时都会检查集合的修改次数(modCount),如果发现不一致就会抛出异常。import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
// 使用for-each循环遍历
for (String s : list) {
System.out.println(s);
// 这里不会抛出ConcurrentModificationException
}
// 使用迭代器遍历
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
System.out.println(s);
// 这里也不会抛出ConcurrentModificationException
}
// 如果在遍历过程中直接修改集合,会抛出ConcurrentModificationException
for (String s : list) {
if (s.equals("B")) {
list.remove(s); // 抛出异常
}
}
}
}
remove()
方法:在遍历过程中,如果需要删除元素,应该使用迭代器的remove()
方法,而不是直接调用集合的remove()
方法。Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if (s.equals("B")) {
iterator.remove(); // 正确的方式
}
}
ConcurrentHashMap
、CopyOnWriteArrayList
等。List<String> copyList = new ArrayList<>(list);
for (String s : copyList) {
if (s.equals("B")) {
list.remove(s); // 不会抛出异常
}
}
通过这些方法,可以有效地避免在遍历集合时抛出ConcurrentModificationException
异常。
领取专属 10元无门槛券
手把手带您无忧上云