Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

540
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!