踩坑記錄--list.remove()方法陷阱

一、首先說正確的方式

1、讓索引同步調整

        for (int i = 0; i < list.size(); i++) {
            Apple apple = list.get(i);
            if(apple.getWeight()==23){
                list.remove(i--);
            }
        }

2、倒序遍歷List刪除元素

        for (int i = list.size() - 1; i >= 0; i--) {
            Apple apple = list.get(i);
            if (apple.getWeight() == 23) {
                list.remove(i);
            }
        }

3、Iterator.remove() 方法會在刪除當前迭代對象的同時,會保留原來元素的索引,建議使用此方式。

        Iterator<Apple> iterator = list.iterator();
        while (iterator.hasNext()) {
            Apple apple = iterator.next();
            if (apple.getWeight() == 23) {
                iterator.remove();
            }
        }

二、錯誤的刪除方式

1、正序遍歷

        for (int i = 0; i < list.size(); i++) {
            Apple apple = list.get(i);
            if(apple.getWeight()==23){
                list.remove(i);
            }
        }

2、迭代遍歷,用list.remove(i)方法刪除元素,拋出異常:java.util.ConcurrentModificationException

        Iterator<Apple> iterator = list.iterator();
        while (iterator.hasNext()) {
            Apple apple = iterator.next();
            if (apple.getWeight() == 23) {
                list.remove(apple);
            }
        }

3、forech刪除,拋出異常:java.util.ConcurrentModificationException

        for (Apple apple : list) {
            if (apple.getWeight() == 23) {
                list.remove(apple);
            }
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章