gpt4 book ai didi

java - ConcurrentModificationException,需要澄清

转载 作者:行者123 更新时间:2023-11-30 05:56:23 26 4
gpt4 key购买 nike

以下模型代码最终出现在 ConcurrentModificationException 中,这种情况发生(据我所知),因为我正在迭代一个我正在修改的集合。

Set<String> data = new HashSet<String>();
data.add("a=1");
data.add("b=2");
data.add("c=3");
data.add("d=4");

for (String s : data) {
data.remove(s);
}

但是到底为什么呢?请帮忙澄清一下

最佳答案

您违反了迭代器的契约。来自 ConcurrentModificationException javadoc ,

If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

关于java - ConcurrentModificationException,需要澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7248211/

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