-3
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);
    }
}
J. Doe
  • 105
  • 1
  • 6
  • 3
    Without seeing any code, and without seeing the stack trace of the exception, how could we possibly help? – JB Nizet Apr 29 '17 at 10:32
  • Use ListIterator instead! – Ankush G Apr 29 '17 at 10:32
  • @JBNizet it is simply a ConcurrentModificationException from calling a method inside the bracket that edits the object p. – J. Doe Apr 29 '17 at 10:34
  • @vvtx used a list iterator with the same result. – J. Doe Apr 29 '17 at 10:36
  • 2
    What does setFaction do? Looks like it must be modifying the list you are iterating on. There are ways around it, but modifying something *while you're iterating on it* is usually a bad idea. – Joni Apr 29 '17 at 10:38
  • Yep - this is entirely dependent on what setFaction is actually doing. I wrote up a quick mock but I was unable to reproduce the problem. – jropella Apr 29 '17 at 10:52

2 Answers2

1

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

M. le Rutte
  • 3,525
  • 3
  • 18
  • 31
1

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--;
                  }
      }
    
Vikrant
  • 178
  • 4