正确遍历删除List中的元素

  1. /** 
  2.  * 使用Iterator的方式也可以顺利删除和遍历 
  3.  */  
  4. public void iteratorRemove() {  
  5.     List<Student> students = this.getStudents();  
  6.     System.out.println(students);  
  7.     Iterator<Student> stuIter = students.iterator();  
  8.     while (stuIter.hasNext()) {  
  9.         Student student = stuIter.next();  
  10.         if (student.getId() % 2 == 0)  
  11.             stuIter.remove();//这里要使用Iterator的remove方法移除当前对象,如果使用List的remove方法,则同样会出现ConcurrentModificationException  
  12.     }  
  13.     System.out.println(students);  
  14. }  

猜你喜欢

转载自blog.csdn.net/a695929533/article/details/51900252
今日推荐