遍歷ArrayList並刪除指定項的一點總結。。
阿新 • • 發佈:2018-12-25
今天寫了一道題,題目是這樣的:
一個ArrayList物件aList中存有若干個字串元素,現欲遍歷該ArrayList物件,刪除其中所有值為"abc"的字串元素,請用程式碼實現。
很簡單,直接上程式碼:
輸出結果為:[a, ab, abcr, abcf, abdc]public class Test1 { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("a"); aList.add("ab"); aList.add("abc"); aList.add("abc"); aList.add("abcr"); aList.add("abc"); aList.add("abcf"); aList.add("abc"); aList.add("abdc"); for(int i = 0;i < aList.size();i++){ if(aList.get(i).equals("abc")){ aList.remove(i); } } System.out.println(aList); } }
也可以使用迭代器來遍歷:
Iterator<String> iter = aList.iterator();
while(iter.hasNext()){
if(iter.next().equals("abc")){
iter.remove();
}
結果與上面相同。
後來改了資料,多加了一個“abc”:
然後再用for迴圈遍歷,結果變為:ArrayList<String> aList = new ArrayList<String>(); aList.add("a"); aList.add("ab"); aList.add("abc"); aList.add("abc"); //多加的一行 aList.add("abcr"); aList.add("abc"); aList.add("abcf"); aList.add("abc"); aList.add("abdc");
[a, ab, abc, abcr, abcf, abdc] 發現有一個“abc”沒有被移除掉。
然而使用迭代器,答案是對的,所有的“abc”都被移除掉了。
原因:檢查後發現。在for迴圈裡,當清除掉前一個“abc”後,索引會指向下一個“abc”,然而還做了i++操作,等於直接將這個“abc”跳了過去去執行後面的步驟,從而使它“逃過法網”。
而迭代器不會有這樣的問題是因為hasNext()方法,原理是指標向後移動,每執行一次it.next(),指標向後移動一次,一個一個的遍歷。
總結:可以在for迴圈中做一點小處理,如下:
每次清除掉“abc”之後執行i--操作,下一回迴圈再執行i++操作,就相當於抵消啦。for(int i = 0;i < aList.size();i++){ if(aList.get(i).equals("abc")){ aList.remove(i); i--; } }
為了避免此類問題的出現,儘量還是用迭代器比較好。