I\'ve an ArrayList in Java of my class \'Bomb\'.
This class has a method \'isExploded\', this method will return true if the bomb has been exploded, else false.
No, you cannot remove inside an Iterator for ArrayList while iterating on it. Here's Javadoc extract :
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
You'll need to get the Bomb using next :
for (Iterator i = bombGrid.listIterator(); i.hasNext();) {
Bomb bomb = (Bomb) i.next();
if (bomb.isExploded()) i.remove();
}
Or if you can get an Iterator<Bomb>
from your bombGrid (is it an ArrayList<Bomb>
?):
Iterator<Bomb> i = bombGrid.listIterator();
while (i.hasNext()) {
Bomb bomb = i.next();
if (bomb.isExploded()) i.remove();
}
This supposes your iterator supports remove
, which is the case for example by the one given by an ArrayList
.
If you use Java 5, use generics:
List<Bomb> bombGrid = ...;
for (Iterator<Bomb> i = bombGrid.iterator(); i.hasNext();) {
if (i.next().isExploded()) {
i.remove();
}
}