When I run the 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 get an exception that says:
java.util.ConcurrentModificationException at java.util.LinkedList$ListItr.checkForComodification(Unknown Source) at java.util.LinkedList$ListItr.next(Unknown Source) at Tester.main(Tester.java:14)
Why am I getting this exception?
Edit: tmpList - LinkedList, each of which node contains an object of type DepConfAttr. I am sorting tmpList based on memory (first highest memory), which is one of the attributes of the DepConfAttr object.
The code above reflects what I'm trying to achieve with the following code
int size = tmpList.size(); int elementBC = 0; // element being checked int startIndex = 1; for (DepConfAttr dca : tmpList) { long maxMem = dca.getMemory(); // Let this be the maximum memory for(int i = startIndex ; i < 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--; }
source share