关于迭代器的在集合遍历中发生的并发修改异常(java.util.ConcurrentModificationException

原因:迭代器是依赖于集合的,相当于集合的一个副本.
当迭代器操作的时候,如果发现和集合不一样,则抛出异常(并发修改异常)


Exception in thread "main" java.util.ConcurrentModificationException:并发修改异常

解决方案:
    方式1: 不使用迭代器
    方式2: 迭代器自身去修改,同步到集合
            List c = new ArrayList(); //创建对象的方式改变
            ListIterator lit = c.listIterator(); //得到的迭代器改变
            lit.add("android"); //迭代器去添加

    方式三:(原始做法)用集合的size(),get(index)方法再用for循环去遍历操作内容

//报错代码(ConcurrentModificationException)代码如下

public class Test01{
public static void main(String[] args) {
    // 创建集合对象
    Collection c = new ArrayList();
    // 添加元素
    c.add("hello");
    c.add("world");
    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);
}
}
//解决方案方式2 代码如下:

public class Test02{
public static void main(String[] args) {
    // 创建集合对象
    List c = new ArrayList();
    // 添加元素
    c.add("hello");
    c.add("world");
    c.add("java");
    ListIterator lit = c.listIterator();
    while(lit.hasNext()) {
        String s = (String)lit.next();
        if(s.equals("java")) {
            lit.add("android");//直接用迭代器进行操作修改
        }
    }
    System.out.println(c);
}
}
注:使用增强for循环同样可能会出现这样的异常,因为其底层同样也是使用了迭代器。

你可能感兴趣的:(关于迭代器的在集合遍历中发生的并发修改异常(java.util.ConcurrentModificationException)