簡體   English   中英

並發修改異常

[英]Concurrent Modification Exception

如何從下面的程序中解決ConcurrentModificationException 我需要一個列表,其中第一個元素是"Znk" ,然后是其后的排序列表。

我知道,我得到這個是因為我要在同一迭代中添加和刪除。 但是我該如何解決並獲得所需的輸出。

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);

    }

}

您不允許在迭代的同時修改集合。 Java通過檢查正在迭代的集合來防止這種情況,並在發現修改后迅速失敗。

使用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();
    }
}

但是請注意,這種方法不是最優的,因為從數組列表中刪除是O(n)操作,導致整體性能為O(n 2 )。 您最好對列表進行兩次迭代-一次將所有"Znk"放在最前面,再一次將其余項放在后面。 這使您的整體性能為O(n)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM