【问题标题】:java.util.ConcurrentModificationException in iterating over TreeSet [duplicate]java.util.ConcurrentModificationException 在遍历 TreeSet [重复]
【发布时间】:2012-04-08 21:42:48
【问题描述】:

可能重复:
ConcurrentModificationException and a HashMap

我收到以下异常

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.TreeMap$PrivateEntryIterator.nextEntry(Unknown Source)
at java.util.TreeMap$KeyIterator.next(Unknown Source)
at Types$AdjList.makeConnected(Types.java:281)
at Main.main(Main.java:56)

在执行以下代码时

public void makeConnected() {
        TreeSet<Node> exploredNodes = new TreeSet<Node>();
        TreeSet<Node> unexploredNodes = new TreeSet<Node>();
for (Node n : unexploredNodes) {
        ...
        exploredNodes.add(n);
        unexploredNodes.remove(n);
        ...
}

我没有像在 HashMap 中那样使用迭代器,而是需要使用一个可以根据某些条件增长或减少的 Set。 我会接受并给所有答案加分。期待如何回复ConcurrentModificationException这个问题怎么解决 谢谢, 索姆纳特

【问题讨论】:

  • @assylias:好的,我看到 TreeSet 有迭代器
  • @assylias:但是 TreeSet 没有 iterator.remove()。你知道如何使用迭代器从 TreeSet 中删除吗?
  • 所有迭代器都有一个 remove 方法。检查上面链接中第一个答案中的第二段代码,并将地图替换为您的集合。

标签: java multithreading collections iterator


【解决方案1】:

for 循环在内部使用迭代器,您不会使用迭代器删除元素。因此,问题。使用迭代器的 remove 方法如下:

for (Iterator iterator = exploredNodes.iterator(); iterator.hasNext();) {
     Node n = (Node) iterator.next();
     unexploredNodes.add(n);         
     iterator.remove();
}

【讨论】:

  • 我无法使用 iterator.hasNext()。它正在弹出一条消息:HTMLDocument.Iterator 类型的方法 hasNext() 未定义
猜你喜欢
  • 2021-09-19
  • 2013-11-16
  • 1970-01-01
  • 2012-05-19
  • 2010-11-07
  • 1970-01-01
  • 2015-05-27
  • 1970-01-01
  • 2019-11-21
相关资源
最近更新 更多