0

I know how to remove an element using the remove() function inside a for loop this way :

 // ArrayList<Particle> particles;

    for(int = 0; i < particles.size(); i++){
     if(condition){
     particles.remove(i)
     }    
    }

but I'd like to know how to do the same thing using this alternative for loop syntax that I find more elegant :

// ArrayList<Particle> particles;

for(Particle p:particles){
 if(condition){
// remove particle
 }
}
Kaspie
  • 187
  • 11

2 Answers2

0

You can't do that because you'll get a ConcurrentModificationException. ConcurrentModificationException is thrown when something you're iterating over is modified.

You need to create an iterator and use that to remove your elements. Here's an example:

Iterator iterator = particles.iterator();
while(iterator.hasNext()) {
    iterator.remove();
    iterator.next();
}
Jaeheon Shim
  • 491
  • 5
  • 14
-2

Use the Iterator class :

Iterator iterator = particles.iterator();
    while(iterator.hasNext()) {
    iterator.remove();
    iterator.next();
}
  • this all works except I get a type mismatch "java.lang.Object" does not match with "Particle" when I try to Particle particle = iterator.next(); do you know how I could resolve this ? Isn't next() suppose to iterate through my array of objects ? – Kaspie Feb 21 '20 at 15:36