Java – the collections remove method does not give a concurrent modification exception
I've read an article about removing elements from the collection from this link
According to my understanding, the iterator deletion method prevents concurrent modification exceptions, and then deletes the collection But method when I try to run the following codede, I can't get the concurrentof applicationexception
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); }
>According to Javadoc, a concurrentmodicationexception is thrown when we try to make any modifications during the itearticle I'm using the collection remove method, but there's still no exception But if I comment on the line daylist remove(“Tuesday”);, An exception is thrown
Can anyone explain what happened behind the scenes in this code?
Solution
If I comment on the line daylist Remove ("Tuesday");, Throw exception
In fact, this is not a problem The problem is that exceptions occur only for intermediate values
The 'for each' loop works as follows,
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(); }
Repeat steps 2 and 3 until hasnext () returns false
If we delete an element from the list, its size will decrease and modcount will increase
If we delete an element during iteration, modcount= Expectedmodcount is satisfied and a concurrentmodificationexception is thrown
But it's strange to delete the penultimate object Let's see how it works in your case
original,
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.
When you delete "d", the size is reduced to 4
cursor = 4 size = 4 --> hasNext() does not succeed and next() is skipped.
In other cases, concurrent modificationexception as modcount will be thrown= expectedModCount.
In this case, this check is not performed
If you try to print elements during an iteration, only four entries are printed Skip the last element
Your question is similar to this question