exception - Why am I getting java.util.ConcurrentModificationException? -


as run following code :

    import java.util.linkedlist;      class tester {       public static void main(string args[]) {         linkedlist<string> list = new linkedlist<string>();         list.add(new string("suhail"));         list.add(new string("gupta"));         list.add(new string("ghazal"));         list.add(new string("poetry"));         list.add(new string("music"));         list.add(new string("art"));          try {             for(string s : list) {             list.add(0,"art");             list.remove(6);             system.out.println(list);         }         }catch(exception exc) {             exc.printstacktrace();         }      } } 

i exception says :

java.util.concurrentmodificationexception     @ java.util.linkedlist$listitr.checkforcomodification(unknown source)     @ java.util.linkedlist$listitr.next(unknown source)     @ tester.main(tester.java:14) 

why getting exception ?

edit : tmplist linkedlist each node contains object of type depconfattr. sorting tmplist on basis of memory (highest memory first), 1 of attribute of object of depconfattr.

the above code reflected trying achieve through following code

int size = tmplist.size();         int elementbc = 0; // element being checked         int startindex = 1;         (depconfattr dca : tmplist) {             long maxmem = dca.getmemory(); // let maximum memory             for(int = startindex ; < size ; i++) {                 depconfattr dcatmp = tmplist.get(i);                 if(maxmem < dcatmp.getmemory()) {                     tmplist.add(elementbc, dcatmp);                     tmplist.remove(i+1);                     maxmem = tmplist.get(elementbc).getmemory();                                         }             }             elementbc++;             startindex++;             size--;         } 

why getting exception ?

you're removing item list other via iterator, while iterating on it. you're adding list while you're iterating on it.

it's not clear you're trying achieve here, other concurrent collections, you'll exception when try that.

one common fix create copy of list first , iterate on that, modifying original go.


Comments

Popular posts from this blog

c++ - Linked List error when inserting for the last time -

java - activate/deactivate sonar maven plugin by profile? -

java - What is the difference between String. and String.this. ? -