为什么我会收到 ConcurrentModificationException? [英] Why do I get a ConcurrentModificationException?
问题描述
为什么我在代码中的指定位置会收到 ConcurrentModificationException?我不知道我做错了什么...... removeMin()
方法被用来定位列表 pq
中的最小值,删除它,并返回它的值
Why do I get a ConcurrentModificationException at the specified location in my code? I cannot figure out what I am doing wrong... The removeMin()
method is being used to locate the min in the list pq
, remove it, and return its value
import java.util.Iterator;
import java.util.LinkedList;
public class test1 {
static LinkedList<Integer> list = new LinkedList<Integer>();
public static void main(String[] args) {
list.add(10);
list.add(4);
list.add(12);
list.add(3);
list.add(7);
System.out.println(removeMin());
}
public static Integer removeMin() {
LinkedList<Integer> pq = new LinkedList<Integer>();
Iterator<Integer> itPQ = pq.iterator();
// Put contents of list into pq
for (int i = 0; i < list.size(); i++) {
pq.add(list.removeFirst());
}
int min = Integer.MAX_VALUE;
int pos = 0;
int remPos = 0;
while (itPQ.hasNext()) {
Integer element = itPQ.next(); // I get ConcurrentModificationException here
if (element < min) {
min = element;
remPos = pos;
}
pos++;
}
pq.remove(remPos);
return remPos;
}
}
推荐答案
一旦从中获取迭代器的集合被修改,则不应认为迭代器可用.(这个限制对于 java.util.concurrent.* 集合类放宽了.)
An Iterator should not be considered usable once the Collection from which it was obtained is modified. (This restriction is relaxed for java.util.concurrent.* collection classes.)
您首先为pq
获得一个迭代器,然后修改pq
.一旦你修改了 pq
,迭代器 itPQ
就不再有效,所以当你尝试使用它时,你会得到一个 ConcurrentModificationException.
You are first obtaining an Iterator for pq
, then modifying pq
. Once you modify pq
, the Iterator itPQ
is no longer valid, so when you try to use it, you get a ConcurrentModificationException.
一种解决方案是移动 Iterator
在 while
循环之前.更好的方法是完全取消 Iterator 的显式使用:
One solution is to move Iterator<Integer> itPQ = pq.iterator();
to right before the while
loop. A better approach is to do away with the explicit use of Iterator altogether:
for (Integer element : pq) {
从技术上讲,for-each 循环在内部使用迭代器,因此无论哪种方式,只要您不尝试修改循环内的 pq
,此循环才有效.
Technically, the for-each loop uses an Iterator internally, so either way, this loop would only be valid as long as you don’t try to modify pq
inside the loop.
这篇关于为什么我会收到 ConcurrentModificationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!