新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Java集合類ArrayList循環(huán)中刪除特定元素
在項目開發(fā)中,我們可能往往需要動態(tài)的刪除ArrayList中的一些元素。

一種錯誤的方式:
for(int i = 0 , len= list.size();i- if(list.get(i)==XXX){
- 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)
- at ListDemo.main(ListDemo.java:20)
因為你刪除了元素,但是未改變迭代的下標,這樣當?shù)阶詈笠粋€的時候就會拋異???。
可以對上面的程序進行如下改進:
- for(int i = 0 , len= list.size();i
- if(list.get(i)==XXX){
- list.remove(i);
- --len;//減少一個
- }
- }
上面的代碼就正確了。
下面我們再介紹一種方案:
List接口內部實現(xiàn)了Iterator接口,提供開發(fā)者一個iterator()得到當前l(fā)ist對象的一個iterator對象。
- Iterator
sListIterator = list.iterator(); - while(sListIterator.hasNext()){
- String e = sListIterator.next();
- if(e.equals("3")){
- sListIterator.remove();
- }
- }
上面這種也是正確的,并推薦使用第二種方案。
兩種方案實現(xiàn)原理都差多的,第二種只是jdk封裝了下。
查看ArrayList源碼會發(fā)現(xiàn)很多方法內部都是基于iterator接口實現(xiàn)的,所以推薦使用第二種方案。
名稱欄目:Java集合類ArrayList循環(huán)中刪除特定元素
網(wǎng)站地址:http://m.5511xx.com/article/cdhcecp.html


咨詢
建站咨詢
