2015-06-25 5 views
-1

В настоящее время я изучаю структуру Java-коллекции. Но я застрял с итераторами.Iterator remove object property

У меня есть следующий код

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.

+1

Вы уверены, что 'empIt.remove()' когда-либо называется? Вы пробовали переходить через код в вашем отладчике? –

+0

Где находится _Employee_? Но Питер прав: отлаживайте свой код, и вы должны понимать его намного лучше. – PJTraill

ответ

2

Вы никогда не будете делать следующий внутренний цикл. Попробуйте

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

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

    } 
0

Вы должны положить, что Employee current = empIt.next(); внутри цикла и Вы должны удалить его из списка не из итератора

При удалении значения из итератора/списка в цикле он будет бросать 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 
    } 

}