问题描述
当我运行这个时,我得到一个 java.util.ConcurrentModificationException
尽管我使用了 iterator.remove();
When I run this, I get a java.util.ConcurrentModificationException
despite me using iterator.remove();
显然是我在循环中添加了数字 6.发生这种情况是否因为迭代器不知道"它在那里并且无论如何要修复它?
it's obviously me adding the number 6 in the loop. Does this happen because the iterator "doesn't know" it's there and is there anyway to fix it?
public static void main(String args[]){
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
for(Iterator<String> it = list.iterator();it.hasNext();){
String value = it.next();
if(value.equals("4")) {
it.remove();
list.add("6");
}
System.out.println("List Value:"+value);
}
}
推荐答案
ConcurrentModificationException
在调用 String value = it.next();
时被抛出.但真正的罪魁祸首是list.add(6");
.在直接迭代它时,您不得修改 Collection
.您正在使用 it.remove();
这很好,但不是 list.add("6");
.
The ConcurrentModificationException
is thrown when calling String value = it.next();
. But the actual culprit is list.add("6");
. You mustn't modify a Collection
while iterating over it directly. You are using it.remove();
which is fine, but not list.add("6");
.
虽然你可以用 Stream
s 解决问题,但我会先用 Iterator
s 提供一个解决方案,因为这是理解问题的良好第一步.
While you can solve the problem with Stream
s, I will first offer a solution with Iterator
s, as this is a good first step for understanding the problem.
您需要一个 ListIterator;
如果你想在迭代过程中添加和删除:
You need a ListIterator<String>
if you want to add and remove during iteration:
for (ListIterator<String> it = list.listIterator(); it.hasNext();){
String value = it.next();
if (value.equals("4")) {
it.remove();
it.add("6");
}
System.out.println("List Value: " + value);
}
这应该可以解决问题!
使用Stream
s的解决方案:
List<String> newList = list.stream()
.map(s -> s.equals("4") ? "6" : s)
.collect(Collectors.toList());
这里我们创建了一个从您的
.我们List
流式传输映射
所有的值到他们自己,只有4"
被映射到6"
然后我们把它收集回一个列表代码>.但请注意,
newList
是不可变的!
Here we create a Stream
from your List
. We map
all values to themselves, only "4"
gets mapped to "6"
and then we collect it back into a List
. But caution, newList
is immutable!
这篇关于添加到 List 时抛出 java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!