Cannot find a class or type named “Iterator”

<
ArrayList particles;

void setup(){
size(200,200);
particles = new ArrayList();
}
void draw(){
background(255);
particles.add(new Particle(new PVector(width/2,50)));
Iterator it = particles.iterator();
while(it.hasNext()){
Particle p = it.next();
p.run();
if(p.isDead()){
it.remove();
}
}
}
class Particle{
PVector location;
PVector velocity;
PVector acceleration;
float lifespan;

Particle(PVector l){
acceleration = new PVector(0,0.05);
velocity = new PVector(random(-1,1),random(-2,0));
location = l.copy();
lifespan = 255.0;
}

void run(){
update();
display();
}

void update(){
velocity.add(acceleration);
location.add(velocity);
lifespan -= 2.0;
}

void display(){
stroke(0,lifespan);
fill(0,lifespan);
ellipse(location.x,location.y,8,8);
}

boolean isDead(){
if(lifespan < 0.0){
return true;
}else{
return false;
}
}
}

Hello,

Please follow these instructions as a courtesy to this community:
https://discourse.processing.org/faq#format-your-code

I have come across this example before and was able to correct it with some research.

Processing 4.0b7 shows this console message:

After you add the import you will get this error:

A search in this forum for that line 23 (above picture) will find a topic that will give you some insight.

The steps I took worked to resolve this issue:

image

:)

2 Likes

As @glv’s already pointed out, you need to import the Iterator interface before using it:
import java.util.Iterator;

Alternatively you can use a regular for ( ; ; ) loop, but making sure to decrease its iterator variable each time you invoke method remove():

for (int i = 0; i < particles.size(); ++i) {
  final Particle p = particles.get(i);
  p.run();
  if (p.isDead())  particles.remove(i--);
}

It’s even simpler if you iterate it backwards, so you don’t have to worry about decreasing the iterator for each remove():

for (int i = particles.size(); i-- > 0; ) {
  final Particle p = particles.get(i);
  p.run();
  if (p.isDead())  particles.remove(i);
}

For a more complex but more efficient (b/c we completely avoid container’s element left-shifting) backwards technique, see this sketch’s mousePressed() code block implementation:

4 Likes

(post deleted by author)

OH YEA !! Very thank you for your help :no_mouth:

2 Likes

I learned it with your help So THANKS! :slightly_smiling_face:

2 Likes