如何获取自定义对象的并发修改异常arraylist

时间:2013-05-12 07:58:12

标签: arraylist

根据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);
你可以帮我理解这背后的逻辑吗? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

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