java – Collections remove方法不给出Concurrent Modification Exception

前端之家收集整理的这篇文章主要介绍了java – Collections remove方法不给出Concurrent Modification Exception前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经阅读了一篇关于从 this link删除集合中的元素的文章

根据我的理解迭代器删除方法防止并发修改异常然后删除Collection.But的方法当我尝试运行下面的codde我无法得到concurrentmoficationexception

List dayList= new ArrayList();
     dayList.add("Sunday");
     dayList.add("Monday");
     dayList.add("Tuesday");
     dayList.add("Wednesday");
     dayList.remove("Tuesday");
     Iterator itr=dayList.iterator();
        while(itr.hasNext())
        {
           Object testList=itr.next();
           if(testList.equals("Monday"))
             {
            dayList.remove(testList);

             }
    }
    System.out.println(dayList);
}

>根据javadoc,当我们尝试在iteartion期间进行任何修改时抛出ConcurrentModicationException.我正在使用集合remove方法,但仍然没有异常.但是如果我注释行dayList.remove(“Tuesday”);,则抛出异常.

任何人都可以解释这段代码中幕后发生的事情吗?

解决方法

如果我评论行dayList.remove(“星期二”);,抛出异常….

其实这不是问题.问题是仅针对中间值发生异常.

‘for each’循环的工作原理如下,

1.It gets the iterator.
2.Checks for hasNext().
public boolean hasNext() 
{
      return cursor != size(); // cursor is zero initially.
}
3.If true,gets the next element using next().

public E next() 
{
        checkForComodification();
        try {
        E next = get(cursor);
        lastRet = cursor++;
        return next;
        } catch (IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
        }
}

final void checkForComodification() 
{
    // Initially modCount = expectedModCount (our case 5)
        if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

重复步骤2和3,直到hasNext()返回false.

如果我们从列表中删除一个元素,它的大小会减少并且modCount会增加.

如果我们在迭代时删除一个元素,则modCount!= expectedModCount得到满足并抛出ConcurrentModificationException.

删除倒数第二个对象很奇怪.让我们看看它在你的情况下是如何工作的.

原来,

cursor = 0 size = 5 --> hasNext() succeeds and next() also succeeds without exception.
cursor = 1 size = 5 --> hasNext() succeeds and next() also succeeds without exception.
cursor = 2 size = 5 --> hasNext() succeeds and next() also succeeds without exception.
cursor = 3 size = 5 --> hasNext() succeeds and next() also succeeds without exception.

在您删除“d”的情况下,大小会减少到4.

cursor = 4 size = 4 --> hasNext() does not succeed and next() is skipped.

在其他情况下,将抛出ConcurrentModificationException
as modCount!= expectedModCount.

在这种情况下,不会进行此检查.

如果在迭代时尝试打印元素,则只打印四个条目.跳过最后一个元素.

您的问题类似于this问题.

猜你在找的Java相关文章