0

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.

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();
        }
    }
}

1 Answer 1

2

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).

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 (final Iterator iterator = programacoesEmpresas.iterator(); iterator.hasNext();)

and for (final Programacao progEmpresa : programacoesEmpresas)

Sign up to request clarification or add additional context in comments.

6 Comments

You're right, the outer loop should be using another list, that was my problem. I should've looked better before asking the question. Thank you.
It's not a possibility, it is indeed a bug on the code. OP should use a second iterator or use another algorithm.
@LuiggiMendoza I meant that iterating over the same list twice (in both inner and outer loops) is probably a bug, which is in addition to the exception causing bug of trying to remove from the list while iterating over it with the enhanced for loop.
No, that's not a bug. Looks like a wrong implementation of the algorithm. Since enhanced for loop uses iterator behind the scenes, the first iterator will support the removal but the second iterator (used in the inner enhanced for loop) is not recognizing the update of the list, thus throwing the exception. It is not a bug in Java Collections Framework (if that's what you meant) but in the implementation of the algorithm.
@LuiggiMendoza I didn't mean a bug in Java Framework, just a bug in the OP's code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.