删除集合中的元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mingyundezuoan/article/details/83446559

删除集合中的元素


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);
    }
}

猜你喜欢

转载自blog.csdn.net/mingyundezuoan/article/details/83446559