淺談Java list.remove( )方法需要注意的兩個坑
list.remove
最近做項目的過程中,需要用到list.remove()方法,結果發現兩個有趣的坑,經過分析后找到原因,記錄一下跟大家分享一下。
代碼
直接上一段代碼,進行分析。
public class Main { public static void main(String[] args) { List<String> stringList = new ArrayList<>();//數據集合 List<Integer> integerList = new ArrayList<>();//存儲remove的位置 stringList.add('a'); stringList.add('b'); stringList.add('c'); stringList.add('d'); stringList.add('e'); integerList.add(2); integerList.add(4);//此處相當于要移除最后一個數據 for (Integer i :integerList){ stringList.remove(i); } for (String s :stringList){ System.out.println(s); } }}
如上代碼我們有一個5個元素的list數據集合,我們要刪除第2個和第4個位置的數據。
第一次運行
咦,為什么執行兩次remove(),stringList的數據沒有變化呢?
沒有報錯,說明代碼沒有問題,那問題出在哪呢?
仔細分析我們發現,remove()這個方法是一個重載方法,即remove(int position)和remove(object object),唯一的區別是參數類型。
for (Integer i :integerList){ stringList.remove(i); }
仔細觀察上面代碼你會發現,其實i是Integer對象,而由于Java系統中如果找不到準確的對象,會自動向上升級,而(int < Integer < Object),所以在調用stringList.remove(i)時,其實使用的remove(object object),而很明顯stringList不存在Integer對象,自然會移除失敗(0.0),Java也不會因此報錯。
如果我們想使用remove(int position)方法,只能降低對象等級,即修改代碼;
for (Integer i :integerList){ int a =i; stringList.remove(a); }
第二次運行
我們發現提示在坐標為4的地方越界了,這是為什么呢?
其實很簡單,因為執行stringList.remove(2)后,list.size()就-1為4了,我們原來要移除的最后一個位置的數據移動到了第3個位置上,自然就造成了越界。
我們修改代碼先執行stringList.remove(4),再執行執行stringList.remove(2)。
integerList.add(4);
integerList.add(2);
這個錯誤提醒我們:使用remove()的方法時,要先從大到小的位置移除。當然如果你知道具體的對象,直接移除remove(對象)更穩妥。
第三次執行
嗯,這次沒問題了。
總結
1、使用remove()的方法時,要先從大到小的位置移除。當然如果你知道具體的對象,直接移除remove(對象)更穩妥。
2、要密切注意自己調用的remove()方法中的,傳入的是int類型還是一個對象。
補充知識: 關于List.remove()報錯的問題
我們如果想刪掉List中某一個對象,我們可能就會想到會用List.remove()方法。但是這樣如果后續操作這個list的時候就會報錯。
具體的原因是當你操作了List的remove方法的時候,他回去修改List的modCount屬性。
導致拋出異常java.util.ConcurrentModificationException。
最好的想要修改List對象,我們可以用ListIterator。
就像這樣:
ArrayList<Integer> arrayList = new ArrayList<>(); for (int i = 0; i < 20; i++) { arrayList.add(Integer.valueOf(i)); }ListIterator<Integer> iterator = arrayList.listIterator();while (iterator.hasNext()) {if(需要滿足的條件){iterator.remove();//刪除操作iterator.add(integer);//新增操作}}
這樣就不會去修改List的modCount屬性。
以上這篇淺談Java list.remove( )方法需要注意的兩個坑就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
