迭代器删除对象属性

时间:2015-06-25 19:30:21

标签: java

我目前正在学习Java集合框架。但我坚持使用迭代器。

我有以下代码

public static void main(String[] args) {

    List<Employee> list = new LinkedList <Employee>();

    list.add(new Employee("A", "A", "A",
            "A", "A", 1, "A", 1));
    list.add(new Employee("A", "A", "A",
            "A", "A", 1, "A", 2));
    list.add(new Employee("A", "A", "A",
            "A", "A", 1, "A", 3));
    list.add(new Employee("A", "A", "A",
            "A", "A", 1, "A", 4));
    list.add(new Employee("A", "A", "A",
            "A", "A", 1, "A", 5));
    list.add(new Employee("A", "A", "A",
            "A", "A", 1, "A", 6));

    for (Employee a : list) {
        System.out.println(a.getEmployeeID());
    }

    System.out.println("before\n");

    int selectedEmployeesID = 2;

    Iterator<Employee> empIt = list.listIterator();

    Employee current = empIt.next();

    while (empIt.hasNext()) {

        if (current.getEmployeeID() == selectedEmployeesID) {
            empIt.remove();
        }

    }
    for (Employee a : list) {
        System.out.println(a.getEmployeeID());
    }

}

任何人都可以解释为什么迭代器不会从LinkedList中删除。

2 个答案:

答案 0 :(得分:2)

你永远不会做下一个内循环。尝试

Iterator<Employee> empIt = list.listIterator();    

    while (empIt.hasNext()) {
        Employee current = empIt.next();
        if (current.getEmployeeID() == selectedEmployeesID) {
            empIt.remove();
        }

    }

答案 1 :(得分:0)

你必须把Employee current = empIt.next();放在循环中 您必须从列表中删除它而不是从迭代器

中删除它

在循环中从iterator / list中删除值时,它将抛出ConcurrentModificationException。为了在添加或删除列表项时处理,您必须重新分配迭代器

Iterator<Employee> empIt = list.listIterator();    

while (empIt.hasNext()) {
    Employee current = empIt.next();
    if (current.getEmployeeID() == selectedEmployeesID) {
       // empIt.remove();
         list.remove(current);//to remove from list
        empIt = list.listIterator(); //For ConcurrentModificationExceptionHandling  
    }

}