JAVA中Iterator遍曆,添加出現的ConcurrentModificationException異常__JAVA

來源:互聯網
上載者:User
在學習java集合的迭代器遍曆集合內容,並新增內容的時候,遇到了一個ConcurrentModificationException異常,
for(Iterator<String> it=arrList.iterator();it.hasNext();){//System.out.println(it.next());   //當for迴圈結束的時候,it引用就被回收器回收Pattern p=Pattern.compile("風清揚");Matcher m=p.matcher(it.next());if(m.matches()){arrList.add("白娘子");}}

出現了異常,查詢add()方法的源碼:

 ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;
這裡使得modCount的加一

接著我查看next()方法的源碼:

public E next() {            checkForComodification();            int i = cursor;            if (i >= size)                throw new NoSuchElementException();            Object[] elementData = ArrayList.this.elementData;            if (i >= elementData.length)                throw new ConcurrentModificationException();            cursor = i + 1;            return (E) elementData[lastRet = i];        }
看到它調用了一個checkForComodification();方法,查看它的源碼:
final void checkForComodification() {            if (modCount != expectedModCount)//重點在這。。這裡因為modCount的值在add的時候,被加了1,所以不相等,所以會報錯,            //這個就是為了防止在迭代沒有完成的時候,對迭代器所依靠的集合進行修改。。                throw new ConcurrentModificationException();        }
這段代碼的意思就是比較modCount與expectedModCount的值,若值不同則拋出之前遇到的 ConcurrentModificationException()異常。

綜上所訴,當我們調用add()方法是,使得modCount的值加一,這時候與expecteModCount的值不一樣了,所以報錯了。再仔細想一想,這個值得作用就是預防你在

遍曆集合的時候,對集合進行了增加或者刪除操作,而迭代器卻不知道。我們知道,迭代器是依靠集合而存在的,這明顯不符合設計的初衷,所以異常的出現就不足為奇了



解決方案:

一、在你迭代到合格內容是,break()方法,跳出迭代。

二、使用迭代器來進行增加或刪除功能,list集合只有remove()方法可以刪除內容,若要增加內容,就必須使用ArrayList特有的迭代器-ListIterator中的add()方法。

三、使用for迴圈,根據index來遍曆數組





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.