1. 程式人生 > >刪除集合中的元素

刪除集合中的元素

刪除集合中的元素


public class testzhu {
    public static void main(String[] args) {
                
        List<Integer> integerList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8));
        for(int i = 0 ; i < integerList.size() ; i++){
            integerList.remove(i); // 本意是將集合中的元素全部刪除
            // 程式碼執行過程中,集合本身在不斷變更,下標同時也在變更
        }
        System.out.println(integerList);
        // [2, 4, 6, 8]
    }
}

參考資料


注意事項

// 刪除全部元素
// 此時提示異常
public class testzhu {
    public static void main(String[] args) {
                
        List<Integer> integerList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8));
        Iterator<Integer> iterator = integerList.iterator();
        while (iterator.hasNext()){

            iterator.remove();
            // Exception in thread "main" java.lang.IllegalStateException
            //	at java.util.ArrayList$Itr.remove(ArrayList.java:844)
            //	at test.testzhu.main(testzhu.java:23)


        }
        System.out.println(integerList);
    }
}
  • 異常分析
    /**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
  • 直接呼叫 Itr 中的 remove 方法,此時 lastRet 初始化值為 -1 會丟擲異常
  • 需要呼叫 Itr 中的 next 方法
    • cursor 為當前遊標指向
    • 方法內將集合中的元素進行拷貝賦值給了 elementData ,保證原有集合中資料不變
    • lastRet = i 進行出行賦值
  • 呼叫 next 後再呼叫 remove 方法
public class testzhu {
    public static void main(String[] args) {
                
        List<Integer> integerList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8));
        Iterator<Integer> iterator = integerList.iterator();
        while (iterator.hasNext()){
            Integer next = iterator.next();
            if(next % 1 == 0){
                iterator.remove();
            }
        }
        System.out.println(integerList);
    }
}