遍曆List集合,刪除合格元素,list符合條件

來源:互聯網
上載者:User

遍曆List集合,刪除合格元素,list符合條件

List集合的遍曆有三種方式:增強for迴圈,普通for迴圈,Iterator迭代器遍曆

如果只是對集合進行遍曆,以上三種迴圈都可正常遍曆:(1)增強For迴圈遍曆List集合
List<Student> stuList = new ArrayList<Student>();for(Student stu : stuList){    System.out.println(stu.getName());}

 

(2)普通For迴圈遍曆List集合
1 List<Student> stuList = new ArrayList<Student>();2 for(int i = 0;i<stuList.size();i++){3      System.out.println(stuList.get(i).getName());       4 }   

 

(3)迭代器遍曆List集合
List<Student> stuList = new ArrayList<Student>();Iterator iterator = stuList.iterator();while(iterator.hasNext()){    System.out.println(iterator.next().getName());}

 

 

然而,如果我們要遍曆List集合,並刪除合格多個元素,則只能使用Iterator迭代器,其他兩種都會報錯,看下面的例子

(1)增強For迴圈遍曆List集合,並刪除另外一個數組中name相同的元素
List<Student> stuList = new ArrayList<Student>();
String[] names = ["aaa","bbb","ccc"];//此處為舉例子
for(Student stu : stuList){
  for(String name : names){
     if(stu.getName() == name){
        stuList.remove(stu);//第一次刪除沒有問題,當刪除第二個元素的時候,會報ConCurrentModificationException異常
   }
   } }
(2)普通For迴圈遍曆List集合,並刪除另外一個數組中name相同的元素
 List<Student> stuList = new ArrayList<Student>();
String[] names = ["aaa","bbb","ccc"];//此處為舉例子 for(int i = 0;i<stuList.size();i++){
   for(String name : names){
     if(stuList.get(i).getName() == name){
      stuList.remove(i);//第一次刪除沒有問題,當多個刪除的時候,會出現跳過個別元素的情況,不能完全遍曆
   }
   } }
(3)迭代器遍曆List集合,並刪除另外一個數組中name相同的元素
List<Student> stuList = new ArrayList<Student>();
String[] names = ["aaa","bbb","ccc"];//此處為舉例子
Iterator iterator = stuList.iterator(); while(iterator.hasNext()){
  Student stu = itreator.next();
  for(String name : names){
     if(stuList.get(i).getName() == name){
      iterator.remove();//此處採用iterator本身的remove方法,可以完美解決上述問題
   }
   }}
原因:增強for迴圈也是利用內部的iterator來遍曆集合的,Iterator工作在一個獨立的線程中,iterator被建立後,會建立一個單鏈索引表,當原來的對象數量發生變化時,這個索引表的內容不會同步改變,所以當索引指標往後移動時,找不到迭代對象,當iterator工作時,是不允許被迭代的對象改變的,但可以被自身改變,利用Iterator的remove方法進行刪除。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.