关于for循环删除集合元素的几个坑

1.原始的for循环删除集合元素的时候有可能会漏掉某个元素

测试代码:

/**
* 假设需要删除集合中的所有的"A"元素
* 如果使用原始的for循环,那么就可能会漏删
*/
List<String> list = new ArrayList<>();
		
		list.add("A");
		list.add("A");
		list.add("B");
		for(int i=0; i<list.size(); i++) {
			if("A".equals(list.get(i))) {
				list.remove(i);
			}
		}
		System.out.println(list);

输出结果:
[A, B]
可以看到集合中只有一个"A"被删了,第二个"A"却还在。
在这里插入图片描述

其实解决办法也很简单,在删除元素之后再加一行代码i- -就解决了

2.增强型for循环删除集合元素会报出ConcurrentModificationException异常

修改一下上面的测试代码

List<String> list = new ArrayList<>();
		
		list.add("A");
		list.add("A");
		list.add("B");
		for(String item : list) {
			if("A".equals(item)) {
				list.remove(item);
			}
		}
		System.out.println(list);

打印结果是ConcurrentModificationException异常。
增强型for循环其实是编译器认可的语法,在到了虚拟机那边只认迭代器循环,所以在编译为.class文件的时候,最终还是变成了迭代器循环。通过反编译得到如下代码:

List<String> list = new ArrayList();
        list.add("A");
        list.add("A");
        list.add("B");
        Iterator var3 = list.iterator();

        while(var3.hasNext()) {
            String item = (String)var3.next();
            if ("A".equals(item)) {
                list.remove(item);
            }
        }

迭代器这块比较复杂,我们从源码上慢慢探索。
list.iterator()其实际上是获得了一个内部类ListItr对象,而ListItr其实是继承自另一个内部类Itr。循环所用到的hasnext(),next()方法都是在这个类中实现的。

private class Itr implements Iterator<E> {
        /**
         * Index of element to be returned by subsequent call to next.
         */
        int cursor = 0;//这个就是类似于for循环中的int i,当调用了
        //remove方法的时候会让cursor自减,这样可以保证不会漏掉任何一个元素

        /**
         * Index of element returned by most recent call to next or
         * previous.  Reset to -1 if this element is deleted by a call
         * to remove.
         */
        int lastRet = -1;

        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        int expectedModCount = modCount;//modCount是外部类的成员
        //我的理解是这应该代表了该容器的修改次数

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

        public E next() {
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }
        
		//这是迭代器的remove方法
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

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


/**
* ArrayList的remove方法
*/
public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

private void fastRemove(int index) {
        modCount++; //关键代码,这里的modCount自增
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

大概理一下抛出异常的思路:
modCount是集合的成员变量,初始值为1,当创建迭代器对象的时候,modCount会赋值给expectedModCount。当调用了list本身的remove方法的时候,expectedModCount会自增。而到了下一次迭代器的next方法去取集合元素的时候会先执行checkForComodification()方法判断版本号是否一致,如果集合的版本号和迭代器的版本号不一致就会抛出异常。
而如果是调用迭代器的remove方法,它会先调用集合的remove方法,然后执行cursor- -,再把modCount赋值给expectedModCount。这样一来既保证了下一次迭代的时候不会漏过任何元素,也避免了next方法校对版本号的时候抛出异常

猜你喜欢

转载自blog.csdn.net/czx2018/article/details/84770921