[英]Getting ConcurrentModificationException when adding/removing from queue
I have made part of an algorithm below where I need to use a queue, but in Java I can't modify the queue while iterating over it.我在下面需要使用队列的地方做了一部分算法,但是在 Java 中,我无法在迭代队列时修改队列。 I get a
ConcurrentModificationException
.我得到一个
ConcurrentModificationException
。
What I can I do about this?我能做些什么呢? I've been thinking about this for several hours.
我已经考虑了几个小时。
m, n = len(mat), len(mat[0])
visited = [[False] * n for row in range(m)]
q = deque()
destinations = set()
def should_visit(row, col):
"""Return true if (row,col) is a valid position not processed yet"""
return 0 <= row < m and 0 <= col < n and \
mat[row][col] != 'o' and not visited[row][col]
for r in range(m):
for c in range(n):
if mat[r][c] == 'r':
q.append((r, c))
visited[r][c] = True
elif mat[r][c] == 'b':
destinations.add((r, c))
dist = 1 # the level in breadth-first-search.
while q:
for _ in range(len(q)):
(r, c) = q.popleft()
for (new_r, new_c) in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if should_visit(new_r, new_c):
if (new_r, new_c) in destinations:
return dist
q.append((new_r, new_c))
visited[new_r][new_c] = True
dist += 1
You get that exception because you use foreach to loop over the queue.你得到这个异常是因为你使用 foreach 循环队列。 foreach's internal iterator will complain about the
queue.removeFirst()
call. foreach 的内部迭代器会抱怨
queue.removeFirst()
调用。
Using while (.queue.isEmpty()) { var cell = queue;removeFirst();
使用
while (.queue.isEmpty()) { var cell = queue;removeFirst();
will work just fine.会工作得很好。 I don't believe that the foreach loop should even be there.
我不相信 foreach 循环甚至应该在那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.