美文网首页
JAVA Iterator.remove()使用不当 也会产生C

JAVA Iterator.remove()使用不当 也会产生C

作者: martin6699 | 来源:发表于2018-06-09 09:38 被阅读0次

    一直想写,但就是没时间 也是懒吧。终于有点时间写点很久前做项目遇到问题,不是说使用Iterator.remove()不会抛异常嘛,它确实不抛,但会使得在迭代中别的方法抛异常。首先我们来了解下什么是Iterator

    Iterator接口是什么

    Iterator接口提供遍历任何Collection(Set、List、Queue,不包括Map)的接口。

        public interface Iterator {
           boolean hasNext(); // 判断是否有下一个可访问的元素
           Object next(); // 获取集合中下一个元素
           void remove(); // 删除next()方法中返回的元素。
        }
    

    ArrayList中的Iterator实现

    在 ArrayList 内部首先是定义一个内部类 Itr,该内部类实现 Iterator 接口

    cursor 下一个元素的索引位置,lastRet上一个元素索引位置。所以lastRet总比cursor上一位。

    public class ArrayList<E> ... {   
          ...  
    public Iterator<E> iterator() {
            return new 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;
          }
         ...    
        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;      //cursor + 1
                    return (E) elementData[lastRet = i];  //lastRet + 1 且返回cursor处元素
                }    
          ...
        public void remove() {
                if (lastRet < 0)
                    throw new IllegalStateException();
                checkForComodification();
    
                try {
                    ArrayList.this.remove(lastRet);
                    cursor = lastRet;
                    lastRet = -1;
                    // 使用赋值的方式 避免ConcurrentModificationException异常 
                    expectedModCount = modCount;         
                } catch (IndexOutOfBoundsException ex) {
                    throw new ConcurrentModificationException();
                }
            }      
        }
    }
    

    Fail-Fast机制

    快速失败也就是fail-fast,它是Java集合的一种错误检测机制。

    java.util包中的集合类都有 fail-fast 检测,如果fail-fast迭代器检测到在迭代过程中进行了更改操作,那么它会抛出 ConcurrentModificationException。但迭代器中可以使用Iterator.remove() 可以在遍历时移除并不抛异常,但有时候却例外。
    当时做产品分类列表时,表结构及假数据如下,前端大佬要求后端给他们返回一个产品分类列表,每个子分类必须嵌套在父分类json对象里面,那我想到是一次性取出分类list,然后先取出一级分类(parent_id=0),然后根据一级分类递归构建嵌套子分类的分类列表,为了减少方法里面的循环次数,用Iterator.remove(),删除rawCategories里面已经加到父分类上的子分类,但却直接抛出ConcurrentModificationException异常。且看下面部分代码

    category表

    id code name sort parent_id
    1 1 1 2018/1/29 15:50 0
    2 2 2 2018/3/18 15:36 0
    5 1004 5 2018/3/18 15:36 0
    6 1005 6 NULL 1
    9 11001 9 NULL 1
    10 11002 10 NULL 0
    11 11003 11 NULL 6
    12 11004 12 NULL 5
    14 11006 14 NULL 11
    15 11007 15 NULL 9
     public void categoryRecursion(List<ProductCategory> rawCategories, ProductCategory sortCategory) {
    
            // 遍历剩下节点
            Iterator<ProductCategory> rawCategoryIterator = rawCategories.iterator();
            while (rawCategoryIterator.hasNext()) { // A点
               
                ProductCategory rawProductCategory;
                    // 遍历全部
                    // 测试--- 抛ConcurrentModificationException异常 
                    rawProductCategory  = rawCategoryIterator.next();
    
                if (Objects.equals(sortCategory.getId(), rawProductCategory.getParentId())) {
                    // 判断是否属于该分类
                    sortCategory.getChildren().add(rawProductCategory);
    
                    // 测试---
                    rawCategoryIterator.remove(); // C点
                    
                    Iterator<ProductCategory> childSortCategoryIterator = sortCategory.getChildren().iterator();
                    while (childSortCategoryIterator.hasNext()) {
                        // 遍历递归子分类
                        ProductCategory childSortCategory = childSortCategoryIterator.next();
                        categoryRecursion(rawCategories, childSortCategory); // B点
                    }
                } else {
                    continue;
                }
            }
    

    原因就出在rawCategories.iterator()和rawCategoryIterator.next()上。查看了ArrayList的方法,每次调用rawCategories.iterator()都是new一个ArrayList的实现了Iterator内部类Itr, 初始化时会把ArrayList对象的modCount属性值赋给内部类对象expectedModCount属性,那每次递归 调用C点的rawCategoryIterator.remove(), expectedModCount值都会被改变,当B点递归完,回到A点继续遍历时,由于当前的rawCategoryIterator的expectedModCount不变,而modCount在递归而不断改变值,导致在rawCategoryIterator.next()时检查 checkForComodification()发现expectedModCount和modCount不一致,就抛异常了。

    解决方法只能是移除掉C点的代码。

    Java迭代器Iterable接口

    ​ jdk1.5之后新增了Iterable接口用于支持foreach循环,Iterable接口只有一个方法,就是iterator()方法,返回集合的Iterator接口,最终也是使用Iterator接口进行遍历。
    所有实现Iterable接口的对象都可以实现foreach循环操作;

        for (Integer i : list) {
           System.out.println(i);
       }
    

    所以它也有快速失败检测,这也是得注意的地方。

    Iterable接口只是返回了Iterator接口的一个实例,这里很是奇怪,为什么不把两个接口合二为一,直接在Iterable里面定义hasNext(),next()等方法呢?

    原因是实现了Iterable的类可以在实现多个Iterator内部类,例如LinkedList中的ListItrDescendingIterator两个内部类,就分别实现了双向遍历和逆序遍历。通过返回不同的Iterator实现不同的遍历方式,这样更加灵活。如果把两个接口合并,就没法返回不同的Iterator实现类了。

    相关文章

      网友评论

          本文标题:JAVA Iterator.remove()使用不当 也会产生C

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