Don't use iterator. Iterate through the collection backwards like this:
import java.util.ArrayList;
public class RemoveFromCollectionExample {
//
// instance variables
//
private ArrayList<Shark> sharks;
//
// main
//
public static void main(String[] args) {
RemoveFromCollectionExample example = new RemoveFromCollectionExample();
example.sharks = new ArrayList<RemoveFromCollectionExample.Shark>();
example.addShark(false, false, 0, 0);
example.addShark(false, false, 0, 0);
example.addShark(false, false, 0, 0);
example.addShark(false, false, 0, 0);
example.addShark(false, false, 0, 0);
example.addShark(false, false, 0, 0);
example.addShark(false, true, 0, 0);
example.addShark(true, false, 0, 0);
example.addShark(true, false, 0, 0);
example.addShark(true, false, 0, 0);
System.out.println("START WITH: " + example.sharks.size());
example.updateSharks();
System.out.println("Added 1, Removed 3");
System.out.println("ENDED WITH: " + example.sharks.size());
}
//
// update sharks
//
private void updateSharks() {
for (int i = this.sharks.size() - 1; i > 0; i--) {
Shark sharky = this.sharks.get(i);
if (sharky.hasStarved()) {
this.sharks.remove(i);
System.out.println("REMOVED");
} else if (sharky.canBreed()) {
addNewShark(sharky.getX(), sharky.getY());
System.out.println("ADDED");
}
moveShark(sharky);
}
}
//
// add new shark method
//
private void addNewShark(int x, int y) {
this.sharks.add(new Shark(false, false, x, y));
}
private void addShark(boolean hasStarved, boolean canBreed, int x, int y) {
this.sharks.add(new Shark(hasStarved, canBreed, x, y));
}
//
// move method
//
private void moveShark(Shark sharky) {
}
//
// Shark class
//
private class Shark {
private boolean hasStarved;
private boolean canBreed;
private int x;
private int y;
public boolean hasStarved() {
return hasStarved;
}
public void setHasStarved(boolean hasStarved) {
this.hasStarved = hasStarved;
}
public boolean canBreed() {
return canBreed;
}
public void setCanBreed(boolean canBreed) {
this.canBreed = canBreed;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Shark(boolean hasStarved, boolean canBreed, int x, int y) {
super();
this.hasStarved = hasStarved;
this.canBreed = canBreed;
this.x = x;
this.y = y;
}
public void moveShark() {
}
}
}
addNewSharkormoveSharkis to blame here; they probably access the collection in an unsafe way.Iterator.nextis when it checks for commodification (as you can guess from the methods in the trace). It doesn't happen at the point you actually comodify the collection.