Reputation: 85
Okay so in my project for class I'm looking through an ArrayList of my class "Sprite" with an enhanced for loop, and I occasionally need to delete the Sprite that I'm looking at. I'm told I can do this safely (i.e. not deleting the Sprite I'm currently looking at) with Iterators. I looked it up on Oracle's java documentation but I don't really understand it..
Here's my method:
public void forward() {
for (Sprite s : sprites) {
s.move();
for(Sprite x : sprites){
if(s!=x && s.overlaps(x)){
if(s instanceof Razorback && x instanceof Opponent){
x.hit();
}
if(x instanceof Razorback && s instanceof Opponent){
s.hit();
}
}
}
if(s.shouldRemove())
sprites.remove(s);
}
}
if(s.shouldRemove()) is where I need to implement an iterator. If shouldRemove() return true, s needs to be removed from the ArrayList.
Upvotes: 7
Views: 14726
Reputation: 100169
In addition to @Codebender answer: to limit the scope of the iterator variable, you can use plain for
loop:
for(Iterator<Sprite> it = sprites.iterator(); it.hasNext(); ) {
Sprite s = it.next();
...
if (s.shouldRemove())
it.remove();
}
This way the it
variable is undefined after the loop.
Upvotes: 13
Reputation: 14471
You need to loop (and remove) using the iterator itself.
for (Sprite s : sprites) {
should be changed to,
Iterator<Sprite> it = sprites.iterator();
while (it.hasNext()) {
Sprite s = it.next();
And then your if
condition will be,
if (s.shouldRemove())
it.remove();
Upvotes: 11