美文网首页
List 中 subList的踩坑记

List 中 subList的踩坑记

作者: 笨笨翔 | 来源:发表于2019-08-28 14:15 被阅读0次

1. 遇到的问题

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1216)
    at java.util.ArrayList$SubList.listIterator(ArrayList.java:1076)
    at java.util.AbstractList.listIterator(AbstractList.java:299)
    at java.util.ArrayList$SubList.iterator(ArrayList.java:1072)
    at java.util.AbstractCollection.contains(AbstractCollection.java:99)
    at java.util.AbstractCollection.removeAll(AbstractCollection.java:375)
    at com.bleege.basis.task.NotifyTask.main(NotifyTask.java:709)

看异常字面意思是同时操作异常,那么怎么会同时操作呢?

2. 示例代码

    public static void main(String[] args) {
        list8 = Lists.newArrayList(1000L, 1001L, 1003L, 1004L);
        List<List<Long>> lists = CollectionUtil.splitList(list8, 2);
        list8 = lists.get(0);
        list8.removeAll(lists.get(1));
    }

    /**
     * 按指定大小,分隔集合,将集合按规定个数分为n个部分
     * @param <T>
     *
     * @param list
     * @param len
     * @return
     */
    public static <T> List<List<T>> splitList(List<T> list, int len) {
        if (list == null || list.isEmpty() || len < 1) {
            return Collections.emptyList();
        }
        List<List<T>> result = new ArrayList<>();
        int size = list.size();
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<T> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
            result.add(subList);
        }
        return result;
    }

3. 查找原因

这里设计到ArrayList中对subList的实现。查看ArrayList源码

    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);//对subList做检查
        return new SubList(this, 0, fromIndex, toIndex);
        //这里new了一个SubList,那么什么是SubList呢。
    }

由上图可以看出SubList是ArrayList中的一个内部类,咱们在看一下SubList的构造方法

        /**
         *  通过构造方法可以看出,SubList只是通过记录下标来达到目的的。
         *  SubList中存放的对象,实际上还是在父对象中存放的。
         */
        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            this.parent = parent;//由上段代码可以看出,这个parent指向父类
            this.parentOffset = fromIndex;
            this.offset = offset + fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = ArrayList.this.modCount;
        }

      /**
        *  看一下get方法就更明确了
        */
        public E get(int index) {
            rangeCheck(index);
            checkForComodification();
            return ArrayList.this.elementData(offset + index);//这里通过下标,转换为父对象的下标,从而拿到父对象的内容。
        }

那么如何抛出文章开头的异常呢?
这里不得不提到一个属性modCount

    /**
     * The number of times this list has been <i>structurally modified</i>.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in
     * progress may yield incorrect results.
     *
     * <p>This field is used by the iterator and list iterator implementation
     * returned by the {@code iterator} and {@code listIterator} methods.
     * If the value of this field changes unexpectedly, the iterator (or list
     * iterator) will throw a {@code ConcurrentModificationException} in
     * response to the {@code next}, {@code remove}, {@code previous},
     * {@code set} or {@code add} operations.  This provides
     * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
     * the face of concurrent modification during iteration.
     *
     * <p><b>Use of this field by subclasses is optional.</b> If a subclass
     * wishes to provide fail-fast iterators (and list iterators), then it
     * merely has to increment this field in its {@code add(int, E)} and
     * {@code remove(int)} methods (and any other methods that it overrides
     * that result in structural modifications to the list).  A single call to
     * {@code add(int, E)} or {@code remove(int)} must add no more than
     * one to this field, or the iterators (and list iterators) will throw
     * bogus {@code ConcurrentModificationExceptions}.  If an implementation
     * does not wish to provide fail-fast iterators, this field may be
     * ignored.
     */
    protected transient int modCount = 0;
    /** 看注释可以知道,modCount可以简单理解为修改计数 **/

根据实例代码,现在一共有三个对象,一个父对象,两个内部类对象(SubList)。
两个内部类对象各自维护了一个modCount,在实例化内部类对象时,将父对象的modCount的值,赋给了内部类对象。
两个内部类对象在进行removeAll的时候,在第二次遍历并且remove的时候会触发开篇的异常。
由于ArrayList的内部类SubList没有实现自己的removeAll,调用的是父类(AbstractList)的父类(AbstractCollection)的removeAll方法
源码如下:

    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;
        Iterator<?> it = iterator();
        while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

这里在c.contains(it.next())的时候为重点。
由于这里是ArrayList的内部类SubList的对象,SubList没有实现contains 的源码,所以这里的contains还需要在父类(AbstractCollection)中看

    public boolean contains(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return true;
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return true;
        }
        return false;
    }

接下来需要看迭代器的源码,这里SubList有自己的实现只不过也是调用自身的方法。属于一个空壳方法。

private class SubList extends AbstractList<E> implements RandomAccess {
        public Iterator<E> iterator() {
            return listIterator();
        }

        public ListIterator<E> listIterator(final int index) {
            checkForComodification();
            rangeCheckForAdd(index);
            final int offset = this.offset;
            ...//这里还有返回迭代器实例代码,这里隐藏
        }
}

尤其注意checkForComodification();这一句

        private void checkForComodification() {
            if (ArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
        }

这一句判断父对象和内部类对象的参数计数是否一直,如果不一致则抛出异常。
那么他们为什么会不一致呢?
根据上面removeAll的源码,可以知道removeAll是通过迭代器来进行删除的,而这个迭代器是SubList这个内部类自己实现的。咱们查看其自己实现的 迭代器方法。

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

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

SubList.this.remove(lastRet);这一句中,可以看出调用内部类自己的remove()方法
继续跟踪SubListremove()方法

        public E remove(int index) {
            rangeCheck(index);
            checkForComodification();
            E result = parent.remove(parentOffset + index);
            this.modCount = parent.modCount;
            this.size--;
            return result;
        }

this.modCount = parent.modCount;
根据SubListremove的源码可以看出其调用父对象的remove方法,并且将父对象的modCount的值重新赋值给内部类对象。
由于list8.removeAll(lists.get(1))的时候,list8lists.get(1)是两个内部类对象,他们是一个父对象,当list8执行第一次remove之后,lists.get(1)modCount和其父对象的modCount不一致,将导致抛出ConcurrentModificationException异常。
好了终于大工告成了。

subList必然快捷,通过内部类对象和父对象之间的下标关联返回新的引用,其没有进行任何复制操作,
但是如果要用subList出来的内部类对象进行增删操作,最好更为严谨一些。

相关文章

网友评论

      本文标题:List 中 subList的踩坑记

      本文链接:https://www.haomeiwen.com/subject/uelpectx.html