添加到List时抛出java.util.ConcurrentModificationException [英] java.util.ConcurrentModificationException thrown when adding to List
问题描述
当我运行它时,我得到一个 java.util.ConcurrentModificationException
尽管我使用 iterator.remove();
显然我在循环中添加了数字6。这是否会发生,因为迭代器不知道它在那里并且无论如何都要修复它?
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 $ c $调用
。但实际的罪魁祸首是 String value = it.next();
时抛出c> list.add(6);
。在直接迭代它时,不得修改 Collection
。您正在使用 it.remove();
这很好,但不是 list.add(6);
。
你可以解决这个问题,但是你需要一个 ListIterator< String>
这样做。
$ ($ List $)< 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);
}
这应该可以解决问题!
如果我可以提供Java 8替代方案:
列表与LT;字符串> newList = list.stream()
.map(s - > s.equals(4)?6:s)
.collect(Collectors.toList());
在这里,我们从您的<创建流
code>列表。我们 map
所有值都是自己的,只有4
被映射到6
然后我们将它收回到 List
。但请注意, newList
是不可变的!这也是效率较低,但更优雅(imho)。
When I run this, I get a java.util.ConcurrentModificationException
despite me using iterator.remove();
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);
}
}
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");
.
You can however fix this, but you'll need a ListIterator<String>
to do so.
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);
}
This should do the trick!
And if I may offer a Java 8 alternative:
List<String> newList = list.stream()
.map(s -> s.equals("4") ? "6" : s)
.collect(Collectors.toList());
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! This is also less efficient, but a lot more elegant (imho).
这篇关于添加到List时抛出java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!