This is my code, and I obtained a ConcurrentModificationException
when I removed an element. I do not understand why itrGrupo1
is affected by removing an element in itrGrupo2
.
The exception occurs at: Instancia inst1=(Instancia) itrGrupo1.next()
when the second while is finished.
for (int i=0; i<lstPrimeraAgrupacion.size();i++){
List grupo1=new ArrayList();
List grupo2=new ArrayList();
grupo1=(List) lstPrimeraAgrupacion.get(i);
grupo2=(List) lstPrimeraAgrupacion.get(i);
Iterator itrGrupo1 = grupo1.iterator();
while(itrGrupo1.hasNext()) {
List nuevoGrupo=new ArrayList();
Instancia inst1=(Instancia) itrGrupo1.next();
int edad1=Integer.valueOf(inst1.getEdadH());
int carnet1=Integer.valueOf(inst1.getCarnetH());
int antigCli1=Integer.valueOf(inst1.getAntigCli());
Iterator itrGrupo2 = grupo2.iterator();
while(itrGrupo2.hasNext()) {
Instancia inst2=(Instancia) itrGrupo2.next();
int edad2=Integer.valueOf(inst2.getEdadH());
int carnet2=Integer.valueOf(inst2.getCarnetH());
int antigCli2=Integer.valueOf(inst2.getAntigCli());
if(cond){
nuevoGrupo.add(inst2);
itrGrupo2.remove();
}
}
// Put in the final list
if (!nuevoGrupo.isEmpty()){
lstNuevosGrupos.add(nuevoGrupo);
}
}
}
The problem exists due to the following lines:
The first two lines of this create two new
ArrayList
s, but the lines following them makegrupo1
andgrupo2
point to the same, existing list. I feel that this is desired forgrupo2
, since you are modifying it, and it looks like the desired effect of this code is to modifylstPrimeraAgrupacion
'si
th sub-list. (I'm assuming thatlstPrimeraAgrupacion
is aList<List<Instancia>>
, or a list of sub-lists ofInstancia
objects.)What the body of your code does is look through
grupo1
for any elements that match a condition, and then removes them fromgrupo2
. However, if these two variables reference the sameList<Instancia>
object, then modifyinggrupo2
will also change what your iterator overgrupo1
has access to, potentially leaving it in a broken state (which is why you got the exception).Now, there are far better approaches to resolving the problem of iterating over a list and removing elements, but the way that you've designed your code, the lowest-impact solution would be to simply duplicate the elements into a new
List
, and use that as a snapshot of the old list, while you remove elements as needed from the actual list. To do this, you can change the above code to the following: