graf 表示的图;我需要遍历该 HashMap 并设置和删除一些边缘。我怎样才能做到这一点 ?代码给了我这个异常 Exception-6ren">
gpt4 book ai didi

java - 线程 "main"java.util.ConcurrentModificationException 中出现异常 - 遍历集合并删除

转载 作者:行者123 更新时间:2023-12-01 13:06:13 25 4
gpt4 key购买 nike

请帮我解决这个问题。我有由 Structure HashMap> graf 表示的图;我需要遍历该 HashMap 并设置和删除一些边缘。我怎样才能做到这一点 ?代码给了我这个异常

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)


public String vratCestu() {
String vrat = "";
for(String s: this.graf.keySet()){
if (this.graf.get(s).size() != 0)

for(String k : this.graf.get(s)){
this.graf.get(s).remove(k);
this.graf.get(k).remove(s);
vrat += k + "; ";

}
}
return vrat;
}

最佳答案

不要使用增强型 for 循环 for(String s: this.graf.keySet()),而是使用 Iterator使用增强的 for 循环迭代集合时无法修改集合。

关于java - 线程 "main"java.util.ConcurrentModificationException 中出现异常 - 遍历集合并删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23245979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com