java 中list進行動態remove處理

來源:互聯網
上載者:User

標籤:動態刪除   ++   iter   情況   ==   lis   nbsp   remove   bounds   

java中遍曆 list遇到需要動態刪除arraylist中的一些元素 的情況

錯誤的方式

for(int i = 0, len = list.size(); i < len; i++){      if(list.get(i) == 1) {         list.remove(i);      }  }  

這樣會拋出異常

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3      at java.util.ArrayList.RangeCheck(Unknown Source)      at java.util.ArrayList.get(Unknown Source

這個異常是因為刪除元素之後未改變相應角標,遍曆到最後一個 的時候 就會找不到拋出 這個異常

正確做法刪除下標以及定位到遍曆位置

for(int i = 0, len = list.size(); i < len; i++){      if(list.get(i) == 1){         list.remove(i);         len--;       i--;    }  }

或者使用Java的Iterator介面來實現遍曆

Iterator<Integer> iterator = list.iterator();  while(iterator.hasNext()){      int i = iterator.next();      if(i == 1){          iterator.remove();      }  }

 

java 中list進行動態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.