容器遍历时删除元素

在Java中,对于容器的遍历有for循环和爹代器两种方法,其中,for循环有包括了传统的for循环和for each方法。迭代器主要用Uterator(另外还有ListIterator ,双向迭代器;Enumeration,相当于Iterator。现已取代)

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

传统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删除,则会触发`ConcurrentModificationException`错误:

    for (Object e : list) {

                System.out.println(e);

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

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

                }

            }

    运行结果:

    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方法**

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容