0

根据 java doc Java.util.ArrayList 在创建迭代器后更改它的数据结构时会抛出 concurrentModificationException ,但是当我在下面运行代码时它不会抛出相同的

    ArrayList<Employee> lsEmp=new ArrayList<Employee>();
    Employee indra = new Employee(101,"Indra");
    Employee ankit =new Employee(102,"Ankit");
    Employee bhanu= new Employee(103,"bhanu");

    lsEmp.add(indra);
    lsEmp.add(ankit);
    //lsEmp.add(bhanu);

    System.out.println("Employee list"+lsEmp);

    Iterator<Employee> it =lsEmp.iterator();
    if (it.hasNext()){
        Employee temp =  it.next();
        if(temp.getName().equalsIgnoreCase("Indra"));{
            System.out.println("inside if condition");
        //temp.setName("Indra Mohan Joshi");
        lsEmp.remove(temp);
        lsEmp.add(bhanu);
        }
    }

    System.out.println("list after loop"+lsEmp);

你能帮我理解这背后的逻辑吗?提前致谢 !

4

1 回答 1

0

将您if (it.hasNext())的替换为 a ,您会看到出现异常,因为您会在修改列表while (it.hasNext())要求迭代器转到下一个元素。如果未调用迭代器,它不会抛出异常。

于 2013-05-12T08:02:25.723 回答