Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

542
Visualizações
ConcurrentModificationException -> How can I change my code to stop it from throwing this error?
for (FPlayer p : fPlayer.getFaction().getOnline()) {
            p.setFaction(null);   
        }

Basically, the getOnline method returns an array list of the current FPlayers that are online. When the FPlayer is removed from their faction, the faction is set to null (p.setFaction(null)).

I cannot think about how to change my code to stop it from throwing the ConcurrentModificationException. I have used an iterator but still, it.next().setFaction(null) still throws the same exception.

EDIT: USING A LIST ITERATOR:

    ListIterator<FPlayer> it = fPlayer.getFaction().getOnline().listIterator();
    while (it.hasNext()) {
        it.next().setFaction(null);
    }

Caused by: java.util.ConcurrentModificationException

At the line

it.next().setFaction(null)

EDIT #2: Set faction method:

public void setFaction(Faction faction) {
    if (hasFaction()) {
        this.faction.getOnline().remove(this);
    }

    this.faction = faction;
    if (faction != null) {
        this.faction.getOnline().add(this);
    }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Yes, change your code so it doesn't change the collection inside the loop you are running. For example, create a copy of the collection before iterating.

for (Foo foo : new ArrayList(myFoos)) {
   if (foo.isBar()) {
       myFoos.remove(foo);
   }
}

Iterating and changing the list without the new ArrayList() would have caused a ConcurrentModificationException

over 4 years ago · Santiago Trujillo Relatório

0

This is happening because while iterating you are removing the data from the list .

Couple of solutions .

  1. If the list size is small convert it to array and then loop over

  2. Use for loop for iteration .

     for(int i=0;i<fPlayer.getFaction().getOnline().size();i++)
      {
        // Condition to check if true 
           if(true)
              {
               fPlayer.getFaction().getOnline().remove(i);
                i--;
                  }
      }
    
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda