java中List遍歷刪除元素-----不能直接 list.remove()


https://blog.csdn.net/github_2011/article/details/54927531

 

這是List接口中的方法,List集合調用此方法可以得到一個迭代器對象(Iterator)。

for example:

 

[java]  view plain  copy
 
  1. //准備數據  
  2.         List<Student> list = new ArrayList<>();  
  3.         list.add(new Student("male"));  
  4.         list.add(new Student("female"));  
  5.         list.add(new Student("female"));  
  6.         list.add(new Student("male"));  
  7.   
  8.         //遍歷刪除,除去男生  
  9.         Iterator<Student> iterator = list.iterator();  
  10.         while (iterator.hasNext()) {  
  11.             Student student = iterator.next();  
  12.             if ("male".equals(student.getGender())) {  
  13.                 iterator.remove();//使用迭代器的刪除方法刪除  
  14.             }  
  15.         }  

 

這種使用迭代器遍歷、並且使用迭代器的刪除方法(remove()) 刪除是正確可行的,也是開發中推薦使用的。

誤區:

如果將上例中的iterator.remove(); 改為list.remove(student);將會報ConcurrentModificationException異常。

這是因為:使用迭代器遍歷,卻使用集合的方法刪除元素的結果。

 

https://blog.csdn.net/github_2011/article/details/54927531


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM