java--Iterator迭代問題:集合并發訪問異常

來源:互聯網
上載者:User

標籤:stat   nbsp   asn   mod   pre   ext   col   元素操作   rgs   

用Iterator對數組進行迭代後,如果在迭代過程中對數組進行增加元素操作(這裡iterator本身沒有提供增加操作方法)時,就會拋出並發訪問異常:

異常如下:

Exception in thread "main" java.util.ConcurrentModificationException

原因:

因為在對數組進行元素刪除操作時,迭代器並不知道數組發生改變,它還是按原來的數組元素進行迭代,因此就會出現並發異常。

舉例如下:

public static void main(String[] args) {        List<String> list=new LinkedList();        list.add("aaaaa");        list.add("bbbbb");        list.add("ccccc");        Iterator it=list.iterator();        while (it.hasNext()) {            String name=(String) it.next();            list.add(name);//這裡對數組進行刪除        }    }

糾正此異常:

Iterator的子類:listiterator

 

public static void main(String[] args) {        List<String> list=new LinkedList();        list.add("aaaaa");        list.add("bbbbb");        list.add("ccccc");        ListIterator it=list.listIterator();        while (it.hasNext()) {            String name=(String) it.next();            it.add("sssssss");//用listiterator自身提供的方法對其進行增刪改查  就不會出現異常。        }    }

 

java--Iterator迭代問題:集合并發訪問異常

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.