foreach - Java list's .remove method works only for second last object inside for each loop -
i seeing weird behavior.
list<string> li = new arraylist<>(); li.add("a"); li.add("b"); li.add("c"); li.add("d"); li.add("e"); for(string str:li){ if(str.equalsignorecase("d")){ li.remove(str); //removing second last in list works fine } }
but if try remove other second last in list, concurrentmodificationexception. came attention while reading "oracle certified associate java se 7 programmer study guide 2012" incorrectly assumes .remove() works example of removing second last in list.
in list, adding or removing considered modification. in case have made 5 modifications(additions).
‘for each’ loop works follows,
1.it gets iterator. 2.checks hasnext().
public boolean hasnext() { return cursor != size(); // cursor 0 initially. }
3.if true, gets 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() { // modcount = expectedmodcount (our case 5) if (modcount != expectedmodcount) throw new concurrentmodificationexception(); }
repeats steps 2 , 3 till hasnext() returns false.
in case if remove element list , it’s size gets reduced , modcount increased.
if remove element while iterating, modcount != expectedmodcount satisfied , concurrentmodificationexception thrown.
but removal of second last object weird. lets see how works in case.
initially,
cursor = 0 size = 5 --> hasnext() succeeds , next() succeeds without exception.
cursor = 1 size = 5 --> hasnext() succeeds , next() succeeds without exception.
cursor = 2 size = 5 --> hasnext() succeeds , next() succeeds without exception.
cursor = 3 size = 5 --> hasnext() succeeds , next() succeeds without exception.
in case remove ‘d’ , size gets reduced 4.
cursor = 4 size = 4 --> hasnext() not succeed , next() skipped.
in other cases, concurrentmodificationexception thrown modcount != expectedmodcount.
in case, check not take place.
if try print element while iterating, 4 entries printed. last element skipped.
hope made clear.
Comments
Post a Comment