[英]Concurrent Modification Exception
How do I resolve ConcurrentModificationException
from the below program . 如何从下面的程序中解决ConcurrentModificationException
。 I need a list where first element is "Znk"
, and then the sorted listed following it. 我需要一个列表,其中第一个元素是"Znk"
,然后是其后的排序列表。
I understand, I am getting this because I am adding and removing in the same iteration . 我知道,我得到这个是因为我要在同一迭代中添加和删除。 But how do I resolve this and get the desired output. 但是我该如何解决并获得所需的输出。
public class ListSwapIndex {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> swapIndex = new ArrayList<String>();
ArrayList<String> swapIndextemp = new ArrayList<String>();
swapIndex.add("Ank");
swapIndex.add("Znk");
swapIndex.add("Bnk");
swapIndex.add("Dnk");
swapIndex.add("Enk");
swapIndex.add("Lnk");
for (String string : swapIndex) {
if(string.equals("Znk")){
swapIndextemp.add(string);
swapIndex.remove(string);
}
}
swapIndextemp.addAll(swapIndex);
System.out.println(swapIndextemp);
}
}
You are not allowed to modify a collection concurrently with iterating it. 您不允许在迭代的同时修改集合。 Java protects from this by checking the collection being iterated, and failing quickly when a modification is found. Java通过检查正在迭代的集合来防止这种情况,并在发现修改后迅速失败。
Using ListIterator<T>
instead of iterating with for
-each loop fixes the problem, because list iterator of ArrayList
allows deletions: 使用ListIterator<T>
而不是使用for
-each循环进行迭代可解决此问题,因为ArrayList
列表迭代器允许删除:
for (ListIterator<String> iter=swapIndex.listIterator(); iter.hasNext() ; ) {
String current = iter.next();
if(current.equals("Znk")){
swapIndextemp.add(string);
iter.remove();
}
}
Note, however, that this approach is suboptimal, because removal from an array list is an O(n) operation, resulting in O(n 2 ) overall performance. 但是请注意,这种方法不是最优的,因为从数组列表中删除是O(n)操作,导致整体性能为O(n 2 )。 You would be better off iterating the list twice - once to put all "Znk"
s at the front, and once more to put the rest of the items after it. 您最好对列表进行两次迭代-一次将所有"Znk"
放在最前面,再一次将其余项放在后面。 This gives you an overall performance of O(n). 这使您的整体性能为O(n)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.