清空一个list不借助于list自身的clear方法,使用for循环、foreach、Iterator来清空list。

1、创建一个集合

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
System.out.println("原始list:" + list);

2.1、for循环正序遍历移除元素(遍历i要定义为int类型,list的remove方法参数为int时视为移除索引为i的元素,参数为Integer时视为移除元素等于i的元素)

//正序遍历移除元素
for (int i = 0; i < list.size(); i++) {
    list.remove(i);
}
System.out.println("for循环正序遍历移除元素结果:" + list);

结果:运行正常,结果不符合预期

原始list:[1, 2, 3, 4]
for循环正序遍历移除元素结果:[2, 4]

原因:for循环遍历移除list元素时,list内部结构也在发生变化,size在减小。

当移除了一个元素1后,list变为[2,3,4],再次遍历删除第二个元素时,程序删除的是新list的第二个元素3,而不是我们期望的元素2。【漏删】

当移除了两个元素后,判断条件 i=2, list.size()=2跳出循环。【未删除完成就跳出】

代码没有按照预想移除所有元素。

2.2、for循环倒序遍历移除元素

//倒序遍历移除元素
for (int i = list.size()-1; i >= 0 ; i--) {
    list.remove(i);
}
System.out.println("for循环倒序遍历移除元素结果:" + list);

运行结果:运行正常,结果符合预期

 原始list:[1, 2, 3, 4]
for循环倒序遍历移除元素结果:[]

原因:每次删除list最后一个元素,就不会出现漏删元素、提前跳出循环的情况,且所有元素依次被删除。

3.1、foreach循环移除元素

for (Integer integer : list) {
    list.remove(integer);
}
System.out.println("foreach循环遍历移除元素结果:" + list);

运行结果:运行失败,抛出异常:ConcurrentModificationException

原始list:[1, 2, 3, 4]
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:911)
    at java.util.ArrayList$Itr.next(ArrayList.java:861)
    at Test.RemoveListTest.removeByForeach(RemoveListTest.java:33)
    at Test.RemoveListTest.main(RemoveListTest.java:13)

原因:通过报错可以看出ArrayList类中Itr.checkForComodification方法报错,位置再911行(下边代码倒数第三行)

看源码:

/**
     * 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;

        Itr() {}

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

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

ArrayList内部重新实现Iterator迭代器的方法,并且添加了checkForComodification方法用来校验修改次数是否和预期值一致,调用迭代器的remove和next方法都用调用checkForComodification方法进行检测。

checkForComodification方法:判断modCount与expectedModCount是否相等。

modCount是AbstractList类的常量,add和remove操作都会使modCount + 1。

expectedModCount值等于创建迭代器时modCount的值。

使用迭代器进行循环遍历会调用next方法,第一次next后modCount值会+1,进行第二次遍历的时候,迭代器调用next方法,next调用checkForComodification方法时,发现modCount与expectedModCount值不相等,因此抛出异常。

通过源码我们可以看出,迭代器内部实现的remove方法有重置expectedModCount值,因此我们可以使用迭代器内部的remove方法,而不是list自己的remove方法,来实现元素移除操作。

3.2、foreach循环移除元素【修改】

for (Iterator iterator = list.iterator(); iterator.hasNext();) {
    iterator.remove();
}
System.out.println("foreach循环遍历移除元素结果:" + list);

运行结果:运行失败,抛出异常:IllegalStateException

原始list:[1, 2, 3, 4]
Exception in thread "main" java.lang.IllegalStateException
    at java.util.ArrayList$Itr.remove(ArrayList.java:874)
    at Test.RemoveListTest.removeByForeach(RemoveListTest.java:40)
    at Test.RemoveListTest.main(RemoveListTest.java:14)

原因:从3.1中ArrayList中实现的迭代器源码可以看出,它还维护了类型为int的lastRet属性和cursor属性。

cursor:返回next元素之后位置的索引,初始值为0。

lastRet:返回next元素之前位置的索引,如果没有就返回-1,且给的默认值为-1。

迭代器的remove方法,它会先判断lastRet是否小于0,是就抛出IllegalStateException异常。

迭代器的next方法,返回cursor指向的元素,lastRet = cursor,cursor下移一位+1。

直接调用remove方法时,lastRet值为-1,所以会抛出异常。

我们可以先调用next方法,然后再调用remove方法就可以避免这种异常产生。

3.3、foreach循环移除元素【修改plus】

for (Iterator iterator = list.iterator(); iterator.hasNext();) {
    iterator.next();
    iterator.remove();
}
System.out.println("foreach循环遍历移除元素结果:" + list);

运行结果:运行正常,结果符合预期

原始list:[1, 2, 3, 4]
foreach循环遍历移除元素结果:[]

4、Iterator遍历移除元素

Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()){
    iterator.next();
    iterator.remove();
}
System.out.println("Iterator遍历移除元素结果:" + list);

运行结果:运行正常,结果符合预期

原始list:[1, 2, 3, 4]
Iterator遍历移除元素结果:[]

原因:原理同3.x一样。

5、附上所有代码

import java.util.*;

public class RemoveListTest {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
        System.out.println("原始list:" + list);
        removeByFor(list);
//        removeByForeach(list);
//        removeByIterator(list);


    }

    private static void removeByFor(List<Integer> list) {
        //正序遍历移除元素。正常运行,不符合预期
//        for (int i = 0; i < list.size(); i++) {
//            list.remove(i);
//        }
//        System.out.println("for循环正序遍历移除元素结果:" + list);
        //倒序遍历移除元素。正常运行,符合预期
        for (int i = list.size()-1; i >= 0 ; i--) {
            list.remove(i);
        }
        System.out.println("for循环倒序遍历移除元素结果:" + list);
    }

    private static void removeByForeach(List<Integer> list) {
        //实际上调用ArrayList的内部foreach方法。抛出异常:ConcurrentModificationException
//        for (Integer integer : list) {
//            list.remove(integer);
//        }
        //直接用迭代器的remove方法。抛出异常:IllegalStateException
//        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
//            iterator.remove();
//        }

        //先调用next方法,再调用remove方法,避免IllegalStateException异常的产生
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            iterator.next();
            iterator.remove();
        }
        System.out.println("foreach循环遍历移除元素结果:" + list);
    }

    private static void removeByIterator(List<Integer> list) {
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()){
            iterator.next();
            iterator.remove();
        }
        System.out.println("Iterator遍历移除元素结果:" + list);
    }
}