Possible Duplicate:
Concurrent modification error when adding elements to LinkedList
i've a arraylist of linkedlist
List<LinkedList<File1>> backup = new ArrayList<LinkedList<File1>>();
during runtime on clicking a button i want to remove few elements from a list and the add them in other list. i also tried declaring the linked list as
List<LinkedList<File1>> lists = Collections.synchronizedList(new ArrayList<LinkedList<File1>>());
bt still the error remains the same . im not able to figure out the error , im also new to java so plz do help . My code is as follows.
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// When delete button is clicked
int parent_node = 0, d =0 ;
File1 srt[] ;
File1 deleted[] = new File1[no_node];
Random randomGenerator = new Random();
int rand_no = 0;
while(rand_no == 0)
{
rand_no = randomGenerator.nextInt(no_node);
}
System.out.println("random no : " + rand_no);
for(i=0;i<backup.size();i++)
{
ListIterator itr = it_bk.get(i);
while(itr.hasNext())
{
File1 file = (File1) itr.next();
if(rand_no == file.nod)
{
parent_node = i;
itr.remove();
}
}
//iterating back
while(itr.hasPrevious())
{
File1 file = (File1) itr.previous();
}
}
System.out.println("Parent node:" + parent_node);
//add the nodes to parent
ListIterator itr1 = it_bk.get(rand_no);
System.out.println("randam node");
while(itr1.hasNext())
{
File1 file = (File1) itr1.next();
deleted[d] = new File1();
deleted[d] = file ;
d++;
//tmp_bk.add(file);
System.out.println("node :" + file.nod + "\tdist :" + file.dist);
}
LinkedList<File1> tmp_bk = backup.get(parent_node);
for(j=0;j<d;j++)
{
tmp_bk.add(deleted[j]);
System.out.println(deleted[j].nod + "\t" + deleted[j].dist);
}
//it_bk.add(tmp_bk.listIterator());
ListIterator itr_p = it_bk.get(parent_node);
System.out.println("parent node");
while(itr_p.hasNext())
{
File1 file = (File1) itr_p.next();
System.out.println("node :" + file.nod + "\tdist :" + file.dist);
}
}
You are traversing through the list and modifying the same list that is not valid,
itr.remove();
Manage two list instead, and after iteration apply effect of resultant list to the source list
The error occurs when you remove objects from a List while iterating over it.
You could put the items you want to remove in another list and after the iteration over the first one just call firstlist.removeAll(list_with_items_to_remove)
.