迭代器的并发修改异常详解

迭代器的并发修改异常

我的理解

1.迭代器遍历集合对象
遍历过程中若使用集合的方法修改集合(如在遍历过程中调用集合的add方法添加一个元素)
就会发生并发修改异常

2.迭代器遍历集合对象
遍历过程中若使用迭代器的方法修改集合(如在遍历过程中调用迭代器的remove方法移除一个元素)
就不会发生并发修改异常

代码演示

public void testIteratorException() {
    
    
        List<Integer> list = new ArrayList<Integer>();
        // 快速添加数据 到 list对象
        Collections.addAll(list, 1, 2, 100, 30, 5, 55);
        System.out.println(list);
        //迭代器对象it
        final Iterator<Integer> it = list.iterator();
        //遍历it迭代器中的值
        while(it.hasNext()) {
    
    
            //输出当前it的值
            final Integer curr = it.next();
            System.out.println(curr);

            if (curr == 100) {
    
    
                // 使用迭代器时候 进行 添加操作
                // list.add(101); 在遍历过程中调用集合的add方法对集合进行修改
                list.add(101);
            }
        }
        System.out.println(list);
    }

当遍历到100元素时我们调用集合的添加方法,此时就会发生并发修改异常
在这里插入图片描述
当我们调用的是迭代器的方法时则不会出现此错误
如下所示

public void testListIterator() {
    
    
        List<Integer> list = new ArrayList<Integer>();
        // 快速添加数据 到 list对象
        Collections.addAll(list, 1, 2, 100, 30, 5, 55);
        System.out.println(list);

//        final ListIterator<Integer> listIt = list.listIterator();
        final Iterator<Integer> it = list.iterator();

        while(it.hasNext()) {
    
    
            final Integer curr = it.next();
            System.out.println(curr);
            if (curr == 100) {
    
    
                // 使用迭代器时候 进行 添加操作
                // it.remove(); 在遍历过程中调用迭代器的方法对集合进行修改
                it.remove();
            }
        }
        System.out.println(list);
    }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Hambur_/article/details/110038037