使用迭代器遍歷集合出現ConcurrentModificationException的總結

思路

1.首先建立集合java

2.使用集合對象添加元素sql

3.建立Iterator對象,並進行循環遍歷bash

public class Test {
    public static void main(String[] args) {
        //建立集合對象
        ArrayList<String> al = new ArrayList<String>();
        //添加元素
        al.add("hello");
        al.add("world");
        al.add("java");
        //建立Iterator對象
        Iterator it = al.iterator();
        while(it.hasNext()){    //判斷集合中是否會有下一個元素
            String str = (String) it.next();
            //在此添加一個添加,若是輸出到了"world"就再爲集合添加"sql"元素
            if("world".equals(str)){
                al.add("sql");
            }
        }
        System.out.println(al);
    }
}
複製代碼

這時你會發現程序會出現ConcurrentModificationException異常spa

經過定位錯誤的位置,能夠知道是String str = (String) it.next();的錯誤。

能夠經過查看iterator的源碼得知是由於當前的數量和預期的數量不一致致使的錯誤

錯誤的緣由:在使用iterator遍歷集合時,咱們又使用ArrayList對象向集合中添加元素形成的。code

解決方式:經過使用ListIterator接口的迭代器解決cdn

public class Test {
    public static void main(String[] args) {
        ArrayList<String> al = new ArrayList<String>();
        al.add("hello");
        al.add("world");
        al.add("java");
        //ListIterator是Iterator的擴展
        ListIterator<String> li = al.listIterator();
        while(li.hasNext()){
            String str = li.next();
            if("world".equals(str)){
                li.add("sql");
            }
        }
        System.out.println(al);
    }
}
複製代碼

這裏須要注意add()方法要使用ListIterator的迭代器對象進行添加對象

這樣問題就完美的解決了blog

相關文章
相關標籤/搜索