ConcurrentModificationException和HashSet.iterator() [英] ConcurrentModificationException and HashSet.iterator()

查看:264
本文介绍了ConcurrentModificationException和HashSet.iterator()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环,如

I have a for loop like

      for (int neighbour : neighbours) {

我可以在循环中修改邻居。发现这就是 ConcurrentModificationException 的原因。并阅读 https://stackoverflow.com/a/8189527/292291

Where I may modify neighbours within the loop. Found that thats the cause of ConcurrentModificationException. And read from https://stackoverflow.com/a/8189527/292291


因此,如果你想修改列表(或一般的任何集合),
使用迭代器,因为它知道修改因此
将妥善处理。

Hence if you want to modify the list (or any collection in general), use iterator, because then it is aware of the modifications and hence those will be handled properly.

所以我试过:

neighboursItr = neighbours.iterator();
while (neighboursItr.hasNext()) {
  // try disconnecting vertices
  neighbour = neighboursItr.next();

但这并不能解决问题。为什么?

But that doesnt fix the problem. Why?

推荐答案

你打电话给 neightbours.remove(邻居)?在那种情况下,这就是问题所在。你需要调用 neightboursItr.remove()

Are you calling neightbours.remove(neighbour)? In that case, that is the problem. You need to call neightboursItr.remove() instead.

这篇关于ConcurrentModificationException和HashSet.iterator()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆