迭代器错误处理

并发修改异常

Exception in thread "main" java.util.ConcurrentModificationException

具体原因:迭代器是依赖与集合的,相当于集合的一个副本,当迭代器在操作的时候,如果发现和集合不一样(元素个数),则输出异常

public class InteratorDeom3 {
    public static void main(String[] args) {
        //method1();
        
        Collection c =new ArrayList();
        
        //List c =new ArrayList();
        c.add("hello");
        c.add("wold");
        c.add("java");
        
        //通过遍历获取集合中的每一个元素,然后进行比较即可
        Iterator it =c.iterator();
        while(it.hasNext()) {
            String s =(String)it.next();//转成字符串类型
            if(s.equals("java")) {
                c.add("android");
            }
        }
    System.out.println(c);
    }

处理:

不使用迭代器
在使用迭代器在进行遍历的时候使用迭代器来遍历

使用第二种方法处理:

public class InteratorDeom3 {
    public static void main(String[] args) {
        //method1();
        
        //Collection c =new ArrayList();
        
        List c =new ArrayList();
        c.add("hello");
        c.add("wold");
        c.add("java");
        
        //通过遍历获取集合中的每一个元素,然后进行比较即可
        /*Iterator it =c.iterator();
        while(it.hasNext()) {
            String s =(String)it.next();//转成字符串类型
            if(s.equals("java")) {
                c.add("android");
            }
        }*/
        
        ListIterator Lit =c.listIterator();
        while(Lit.hasNext()) {
            String s =(String)Lit.next();//获取元素
            if(s.equals("java")) { //进行判断
                Lit.add("android"); //使用迭代器去添加
        }
        
        System.out.println(c);
    }
原文地址:https://www.cnblogs.com/kun19/p/11062301.html