[英]Why removing element from list using iterator causes ConcurrentModificationException?
The code is in portuguese, i'm sorry about that. 代码是葡萄牙语,对此我感到抱歉。
I read in another question here at SO that the exception was being thrown because I was using progSelecionada.remove()
, so I changed toi iterator.remove()
but the error remains. 我在SO的另一个问题中读到,由于我使用的是
progSelecionada.remove()
而引发了异常,因此我将其更改为iterator.remove()
但错误仍然存在。
Can someone explain to me what I may be doing wrong? 有人可以向我解释我可能做错了什么吗?
final List<Programacao> programacoesASeremRemovidas = new ArrayList<Programacao>(
this.programacoesDaEscala.size());
programacoesASeremRemovidas.addAll(this.programacoesDaEscala);
final List<Programacao> programacoesEmpresas = Cache.getInstance().getProgramacoes(
this.empresasSelecionadas);
for (final Iterator<Programacao> iterator = programacoesEmpresas.iterator(); iterator.hasNext();)
{
final Programacao progSelecionada = iterator.next();
for (final Programacao progEmpresa : programacoesEmpresas)
{
if (progSelecionada.getId() == progEmpresa.getId())
{
iterator.remove();
}
}
}
You probably have a bug, since both your loops iterate on the same list programacoesEmpresas
, so even if you didn't get an exception, you would simply remove all the objects from the list (assuming you are not comparing Strings with ==
- I don't know what the type of getId()
is). 您可能有一个错误,因为两个循环都在同一个列表中迭代
programacoesEmpresas
,所以即使您没有遇到异常,也可以从列表中删除所有对象(假设您没有将String与==
进行比较-我不知道getId()
的类型是什么)。
You can't modify that list while iterating over it with the enhanced for loop (which is what you do in the internal loop). 在使用增强的for循环(在内部循环中进行的操作)对其进行迭代时,无法修改该列表。
for (final Iterator iterator = programacoesEmpresas .iterator(); iterator.hasNext();) 为(最终迭代器迭代器= programacoesEmpresas .iterator(); iterator.hasNext();)
and for (final Programacao progEmpresa : programacoesEmpresas ) 并且用于(最终Programacao progEmpresa: programacoesEmpresas )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.