美文网首页
<>集合元素删除

<>集合元素删除

作者: monk87 | 来源:发表于2019-05-25 18:26 被阅读0次

背景

众所周知 ,在对集合进行遍历的时候删除元素,会抛出异常 ConcurrentModificationException.本文对这个问题进行探讨下,并提出几个删除的方式。

为啥会报错

ArrayList为例,来说明下这个问题

删除的例子

List<User> strings = new ArrayList<>();
        strings.add(new User("a",1));
        strings.add(new User("b",2));
        strings.add(new User("c",3));
        //jdk
        Iterator<User> iterator = strings.iterator();
        while (iterator.hasNext()) {
            User next = iterator.next();
            if (next.getName().equals("a")) {
                strings.remove(next);
//                System.out.println("nwo remove");
//                iterator.remove();
            }
        }

这个代码执行的时候,会报错如下

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 cn.zuosh.tessb.service.TestIterator.main(TestIterator.java:20)

原因分析

iterator 迭代的时候 会检查当前list的状态是否正确,如果检查未通过,则直接报错。代码如下:

      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];
        }
    //检查的时候会有这2个值是否相等的判断
      final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

从上面的代码可以发现 ,主要是有2个属性导致的 ,modCount expectedModCount,这两个值,在iterator初始化的时候相等,并且随着add/remove等操作,会累加。

// list的remove操作 通过fastRemove完成
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;
    }

//可以看到 ,fastRemove就是把modCount进行了累加
 private void fastRemove(int index) {
        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进行了累加,此时再次迭代执行next的时候,检查状态就会出错。然后就会抛出异常了。

那应该怎么操作?

正确的方式应该如下

      //这个可以正常执行。
       List<User> strings = new ArrayList<>();
        strings.add(new User("a",1));
        strings.add(new User("b",2));
        strings.add(new User("c",3));
        //jdk
        Iterator<User> iterator = strings.iterator();
        while (iterator.hasNext()) {
            User next = iterator.next();
            if (next.getName().equals("a")) {
//                strings.remove(next);
//                System.out.println("nwo remove");
                iterator.remove();
            }
        }

可以看到,上面调用的是 iterator中的remove,为啥这个remov就不会报错了呢

//来自 ArrayList.Itr#remove()
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();
            }
        }

上面的额删除操作,在执行了删除之后维护了两个属性的关系 通过一句expectedModCount = modCount;.因此,在继续迭代执行next的时候,就能正常执行了 。

其他的一些方式

  • for循环遍历list
for(int i=0;i<list.size();i++){
    if(list.get(i).equals("del"))
        list.remove(i);
}

这种方式的问题在于,删除某个元素后,list的大小发生了变化,而你的索引也在变化,所以会导致你在遍历的时候漏掉某些元素。比如当你删除第1个元素后,继续根据索引访问第2个元素时,因为删除的关系后面的元素都往前移动了一位,所以实际访问的是第3个元素。因此,这种方式可以用在删除特定的一个元素时使用,但不适合循环删除多个元素时使用。

  • for each 删除
for(String x:list){
    if(x.equals("del"))
        list.remove(x);
}

这种方式的问题在于,删除元素后继续循环会报错误信息ConcurrentModificationException,因为元素在使用的时候发生了并发的修改,导致异常抛出。但是删除完毕马上使用break跳出,则不会触发报错。

相关文章

  • <>集合元素删除

    背景 众所周知 ,在对集合进行遍历的时候删除元素,会抛出异常 ConcurrentModificationExce...

  • java集合删除元素的方式

    集合删除元素时,java删除会报java.util.ConcurrentModificationException...

  • java集合框架知识点

    java集合框架的知识点接口 集合 元素 java key 阅读2771Java集合框架作为Java编程语言的基础...

  • Python基础(4) - 集合的交集与并集

    集合的基础操作 如何向集合中添加和删除元素 添加元素 移除元素 集合之间的运算 使用或(|)进行合并 会将重复的删...

  • Redis 集合命令汇总

    创建集合&添加集合元素 删除集合元素 查看集合中所有元素 判断集合中是否存在某个元素 随机弹出并删除集合中的元素 ...

  • 2019-04-24

    java.util.LinkedList集合数据存储的结构是链表结构。方便元素添加、删除的集合。 LinkedLi...

  • java中List集合删除元素

    List删除所有指定元素 环境:jdk8 1.概要 java中List使用List.remove()直接删除指定元...

  • Java 删除集合元素的方式

    简介 删除集合中的元素,有两种删除的形式,一种是删除特定元素,一种是删除特定索引的元素。 删除的方式有:使用Jav...

  • 一篇文章,全面解读Android面试知识点

    Java Java基础 Java集合框架 Java集合——ArrayList Java集合——LinkedList...

  • Redis有序集合类型及应用

    有序集合是在集合类型的基础上为每个元素都关联了一个分数,这使我们不仅可以完成插入,删除和判断元素是否存在等集合类型...

网友评论

      本文标题:<>集合元素删除

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