遍历并删除list中的元素

来源:互联网 发布:linux视频编辑器 编辑:程序博客网 时间:2024/06/05 14:12

遍历删除List中的元素有很多种方法,当运用不当的时候就会产生问题。下面主要看看以下几种遍历删除List中元素的形式:

1.通过增强的for循环删除符合条件的多个元素

2.通过增强的for循环删除符合条件的一个元素

3.通过普通的for删除删除符合条件的多个元素

4.通过Iterator进行遍历删除符合条件的多个元素

 

[java] view plain copy
  1.     
  2. public void listRemove() {    
  3.     List students = this.getStudents();    
  4.     for (Student stu : students) {    
  5.         if (stu.getId() == 2)     
  6.             students.remove(stu);    
  7.     }    
  8. }    
[java] view plain copy
  1.     
  2. public void listRemoveBreak() {    
  3.     List students = this.getStudents();    
  4.     for (Student stu : students) {    
  5.         if (stu.getId() == 2) {    
  6.             students.remove(stu);    
  7.             break;    
  8.         }    
  9.     }    
  10. }    
[java] view plain copy
  1.     
  2. public void listRemove2() {    
  3.     List students = this.getStudents();    
  4.     for (int i=0; i
  5.         if (students.get(i).getId()%3 == 0) {    
  6.             Student student = students.get(i);    
  7.             students.remove(student);    
  8.         }    
  9.     }    
  10. }    

[java] view plain copy
  1.     
  2. public void iteratorRemove() {    
  3.     List students = this.getStudents();    
  4.     System.out.println(students);    
  5.     Iterator stuIter = students.iterator();    
  6.     while (stuIter.hasNext()) {    
  7.         Student student = stuIter.next();    
  8.         if (student.getId() % 2 == 0)    
  9.             stuIter.remove();//这里要使用Iterator的remove方法移除当前对象,如果使用List的remove方法,则同样会出现ConcurrentModificationException    
  10.     }    
  11.     System.out.println(students);    
  12. }