java 的集合元素的删除

java 的集合删除

罪恶之根源-设计如此

        ArrayList<Integer> array = new ArrayList<>();
        array.add(1);
        array.add(2);
        array.add(2);
        array.add(3);
        for (Integer a : array) {
    
    
            if (2 == a){
    
    
                array.remove(a);
            }
            System.out.println(a);
        }

上面的代码运行出现下面的ConcurrentModificationException

Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.tom.offer.jcf.LIterrator.main(LIterrator.java:58)

知道的人说这是发生了ConcurrentModificationException的异常。但是这样写为啥就发生异常了呢?
有的人说java集合的删除就是要用迭代器。要这样删除:

        ArrayList<Integer> array = new ArrayList<>();
        array.add(1);
        array.add(2);
        array.add(2);
        array.add(3);
//        for (Integer a : array) {
    
    
//            if (2 == a){
    
    
//                array.remove(a);
//            }
//            System.out.println(a);
//        }

        Iterator<Integer> iterator = array.iterator();
        while(iterator.hasNext()){
    
    
            Integer next = iterator.next();
            if(next == 2){
    
    
                iterator.remove();
            }
        }
        System.out.println();
        array.forEach(v -> System.out.print(v + " ")); //1 3 

原因之谜

原先使用c++的时候,对于iterator++iterator--使用的挺爽,java的iterator.next()到如今还是觉得陌生。
为啥使用迭代器删除就没错,使用集合自己的删除方法就错了呢?
原因在于我觉得是java的集合框架就是这样设计的。迭代器就是这样设计的。
在这里插入图片描述
首先看看 ArrayList的迭代器实现

     /**
     * 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
        // 注意这里是把ArrayList的modCount赋值给了迭代器的expectedModCount 
        int expectedModCount = modCount;

        Itr() {
    
    }

		/**
		 * 仅仅是判断迭代器当前的位置cursor 和ArrayList的size
		 */
        public boolean hasNext() {
    
    
            return cursor != size;
        }
		/**
		 * 就看成是迭代器的iter++
		 */
        @SuppressWarnings("unchecked")
        public E next() {
    
    
            //检查1
            checkForComodification();
            int i = cursor;
            //检查2
            if (i >= size)
                throw new NoSuchElementException();
            //这里真的感觉不好,啥蹩脚语法ArrayList.this.elementData;
            // 没有C++优雅
            Object[] elementData = ArrayList.this.elementData;
            //检查3
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            // 干正事:iter++
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

		/**
		 * 迭代器的删除
		 */
        public void remove() {
    
    
            if (lastRet < 0)
                throw new IllegalStateException();
            //检查1
            checkForComodification();

            try {
    
    
                // 调用ArrayList的remove
                // 他会modCount++,然后移动数组
                ArrayList.this.remove(lastRet);
                // 把lastRet又给了cursor
                cursor = lastRet;
                //赋初值
                lastRet = -1;
                //把在ArrayList.this.remove(lastRet)中
                //修改的modCount又赋值给了expectedModCount
                //太不好的设计了。。。。。。。。。
                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的remove
     */
    public E remove(int index) {
    
    
        rangeCheck(index);

		//!!!!!!!!!!!!!!
        modCount++;
        E oldValue = elementData(index);

        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

        return oldValue;
    }
通过源代码可以知道,iterator的next()方法会调用集合自己的remove()方法。
而集合自己的remove会增加modCount,next()在调用remove()后,
会把集合的modCount赋值给iterator的expectedModCount。
如下:
        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();
            }
        }
因此对于代码块
        for (Integer a : array) {
    
     //这里实际上编译器是处理为迭代器 也就是
            if (2 == a){
    
              //for(Iterator<Integer> iter = 
                                  // array.iterator();iter.hasNext();){
    
    
                array.remove(a);  //      Integer a = iter.enxt();
            }
            System.out.println(a);
        }for循环中,一旦array.remove(a);他就会修改集合自己的modCount,
不会修改迭代器的expectedModCount 。
当再次运行到for循环中的next()checkForComodification()
就会出现ConcurrentModificationException

迭代器删除就没错??

看如下的代码:

        List<String> list = new ArrayList<>();
        list.add("123");
        list.add("456");
        list.add("567");
        list.add("tom");
        list.add("lixi");
        
        System.out.println();
        list.forEach(v -> System.out.print(v + " "));
        
        Iterator<String> first = list.iterator();
        Iterator<String> second = list.iterator();
        for(; first.hasNext();){
    
    
            String next = first.next();
            if(next.equals("tom")){
    
    
                first.remove();
            }
        }
        System.out.println();
        list.forEach(v -> System.out.print(v + " "));
        
        for(; second.hasNext();){
    
    
        //到这里,集合的modCount已经改变很多次了,
        //但是迭代器second的expectedModCount还是最初的modCount,
        //因此second.next()会出现ConcurrentModificationException
            String next = second.next(); 
            if(next.equals("tom")){
    
    
                second.remove();
            }
        }
        System.out.println();
        list.forEach(v -> System.out.print(v + " "));

小结

我认为这样的设计不友好。

猜你喜欢

转载自blog.csdn.net/xiaolixi199311/article/details/111936909