容器遍歷時(shí)刪除元素

在Java中,對(duì)于容器的遍歷有for循環(huán)和爹代器兩種方法,其中,for循環(huán)有包括了傳統(tǒng)的for循環(huán)和for each方法。迭代器主要用Uterator(另外還有ListIterator ,雙向迭代器;Enumeration,相當(dāng)于Iterator?,F(xiàn)已取代)

具體使用方法(以包含Integer元素的 List為例):

傳統(tǒng)for:

? ? ?for(int i=0;i<list.size();i++){

? ? ? ? ? ? ? ? ...

? ? ? ? }

for each:

? ? for(Integer item:list){

? ? ? ? ...

? ? }

迭代器:

? ? ?Iterator item = list.iterator();

? ? ? ? while(? item.hasNext()){

? ? ? ? ? ? Integer?dat = intem.next();

? ? ? ? ? ? ...

? ? ? ? }

在以上三種迭代方法中,如果要一邊遍歷,一邊刪除元素,則必須用迭代器方式。若果使用for each刪除,則會(huì)觸發(fā)`ConcurrentModificationException`錯(cuò)誤:

? ? for (Object e : list) {

? ? ? ? ? ? ? ? System.out.println(e);

? ? ? ? ? ? ? ? if("b".equals(e)){

? ? ? ? ? ? ? ? ? ? list.remove(e);//操作集合的刪除方法

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? 運(yùn)行結(jié)果:

? ? a

? ? b

? ? Exception in thread "main" java.util.ConcurrentModificationException


? ? 修改


? ? Iterator it=list.iterator();

? ? ? ? ? ? while(it.hasNext()){

? ? ? ? ? ? ? ? Object e=it.next();

? ? ? ? ? ? ? ? if("b".equals(e)){

? ? ? ? ? ? ? ? ? ? it.remove();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? System.out.println(list);

**不能使用集合類的remove方法,而是要使用Iterator的remove方法**

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容