java - Why does removing an element from a list throw ConcurrentModificationException? -


this question has answer here:

my program throws concurrentmodificationexception when run following piece of code. through research found element in list cannot added or removed when in iterator loop. do remove element in list<bean>?

for (iterator<entry<string, list<bean>>> iterator = datamap.entryset().iterator(); iterator.hasnext();) {     entry<string, list<bean>> entry = (entry<string, list<bean>>)iterator.next();     list<bean> datewisevalues = (list<bean>) entry.getvalue();     int j = 0;     (bean statbean : datewisevalues) {         (int = 0; < commonelements.size(); i++) {             if(statbean.getdate().equalsignorecase(commonelements.get(i))) {                 //remove bean                 entry.getvalue().remove(j);             }         }         j++;     } }  

rather using range-based for loop on datewisevalues, use iterator explicitly can instead invoke iterator#remove():

for (final iterator<? extends bean> = datewisevalues.iterator();      it.hasnext();) {   final bean statbean = it.next();   (int = 0, last = commonelements.size(); != last; ++i)     if (statbean.getdate().equalsignorecase(commonelements.get(i)))                       it.remove(); } 

in general, it's safe remove elements , underlying collection while iterating on long through 1 of collection's iterators.


though can't see concrete type of datewisevalues, know it's subtype of list. 2 common concrete types implementing list arraylist , linkedlist. prose class-level documentation each of classes contains following admonishment:

the iterators returned class's iterator , listiterator methods fail-fast: if list structurally modified @ time after iterator created, in way except through iterator's own remove or add methods, iterator throw concurrentmodificationexception. thus, in face of concurrent modification, iterator fails , cleanly, rather risking arbitrary, non-deterministic behavior @ undetermined time in future.

note it's warning must use iterator#remove() mutation during iteration or you'll face thrown concurrentmodificationexception next time use same or other iterator walking on same underlying list.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -