如何正確遍歷刪除List中的元素,你會嗎?

遍歷刪除List中的元素有不少種方法,當運用不當的時候就會產生問題。下面主要看看如下幾種遍歷刪除List中元素的形式:java

1.經過加強的for循環刪除符合條件的多個元素this

2.經過加強的for循環刪除符合條件的一個元素spa

3.經過普通的for刪除刪除符合條件的多個元素.net

4.經過Iterator進行遍歷刪除符合條件的多個元素對象

 

[java] view plain copy
  1. /**  
  2.  * 使用加強的for循環  
  3.  * 在循環過程當中從List中刪除非基本數據類型之後,繼續循環List時會報ConcurrentModificationException  
  4.  */    
  5. public void listRemove() {    
  6.     List<Student> students = this.getStudents();    
  7.     for (Student stu : students) {    
  8.         if (stu.getId() == 2)     
  9.             students.remove(stu);    
  10.     }    
  11. }    
[java] view plain copy
  1. /**  
  2.  * 像這種使用加強的for循環對List進行遍歷刪除,但刪除以後立刻就跳出的也不會出現異常  
  3.  */    
  4. public void listRemoveBreak() {    
  5.     List<Student> students = this.getStudents();    
  6.     for (Student stu : students) {    
  7.         if (stu.getId() == 2) {    
  8.             students.remove(stu);    
  9.             break;    
  10.         }    
  11.     }    
  12. }    
[java] view plain copy
  1. /**  
  2.  * 這種不使用加強的for循環的也能夠正常刪除和遍歷,  
  3.  * 這裏所謂的正常是指它不會報異常,可是刪除後獲得的  
  4.  * 數據不必定是正確的,這主要是由於刪除元素後,被刪除元素後  
  5.  * 的元素索引起生了變化。假設被遍歷list中共有10個元素,當  
  6.  * 刪除了第3個元素後,第4個元素就變成了第3個元素了,第5個就變成  
  7.  * 了第4個了,可是程序下一步循環到的索引是第4個,  
  8.  * 這時候取到的就是本來的第5個元素了。  
  9.  */    
  10. public void listRemove2() {    
  11.     List<Student> students = this.getStudents();    
  12.     for (int i=0; i<students.size(); i++) {    
  13.         if (students.get(i).getId()%3 == 0) {    
  14.             Student student = students.get(i);    
  15.             students.remove(student);    
  16.         }    
  17.     }    
  18. }    

 

[java] view plain copy
    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. }   
相關文章
相關標籤/搜索