-6

I have searched for an answer to my problem but nothing has worked. This is my code.

public ArrayList<Exercise> checkList()
{
    Criteria a = this.getCriteria();
    ArrayList<Exercise> z = this.getExercise();
    for(Exercise c : z)
    {
        if(!compareSkillLevel(c,a)|| !compareEquipment(c)|| !compareFocus(c)
                || !compareTraining(c))
            z.remove(c);
    }
    return z; 

}

After running this I get a Conncurrent Modification Exeption.

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at randomworkout.List.checkList(List.java:161)
at Main.main(Main.java:46)

How do I solve this?

user3794468
  • 1
  • 1
  • 4
  • Please search StackOverflow before asking a new question. Just searching for `ConcurrentModificationException` yields very many results. – Erwin Bolwidt Jul 01 '14 at 15:27

2 Answers2

2

As other answers have pointed out, the problem you have here is that you are trying to remove from a list while you iterate over it. This isn't allowed in java, except if you remove the element using the iterator's remove method. This means you have two ways about fixing this code.

1:

for(Iterator<Exercise> iterator = z.iterator(); iterator.hasNext();)
{
    Exercise c = iterator.next();
    if(!compareSkillLevel(c,a)|| !compareEquipment(c)|| !compareFocus(c)
            || !compareTraining(c))
        iterator.remove();
}

or, you can loop over the array list using its index, and instead do something like

2:

for(int i = 0;i < z.size(); i++)
{
    Exercise c = z.get(i);
    if(!compareSkillLevel(c,a)|| !compareEquipment(c)|| !compareFocus(c)
            || !compareTraining(c))
        z.remove(i--)
}

Note the i-- here, which is necessary because the act of removing an element from the ArrayList shifts the existing elements over, meaning the next element you want to examine is in the place of the last element.

clearlyspam23
  • 1,624
  • 13
  • 15
0

You remove while iterating, that causes this exception.
To solve use an Iterator (ListIterator) and call iterator.remove()

for (Iterator<Excercise> it = z.iterator(); it.hasNext();) {
   Excercise e = it.next();
   if (condition) {
      z.remove();
   }
}
AlexWien
  • 28,470
  • 6
  • 53
  • 83