Java list.remove( )方法需要注意的兩個地方__Java

來源:互聯網
上載者:User
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個位置的資料。 第一次運行

我們發現提示在座標為4的地方越界了,這是為什麼呢。
其實很簡單,因為執行stringList.remove(2)後,list.size()就-1為4了,我們原來要移除的最後一個位置的資料移動到了第3個位置上,自然就造成了越界。

我們修改代碼先執行stringList.remove(4),再執行執行stringList.remove(2)。

        integerList.add(4);        integerList.add(2);
這個錯誤提醒我們:使用remove()的方法時,要先從大到小的位置移除。當然如果你知道具體的對象,直接移除remove(對象)更穩妥。 第二次運行

嗯,沒有報錯。但是,咦,為什麼執行兩次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);        }
第三次執行


嗯,這次沒問題了。 總結

使用remove()的方法時,要先從大到小的位置移除。當然如果你知道具體的對象,直接移除remove(對象)更穩妥。

要密切注意自己調用的remove()方法中的,傳入的是int類型還是一個對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.