Kaj
Kaj

Reputation: 2513

Java delete arraylist iterator

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.

Now I'm trying to iterate through this arraylist, call this method isExploded and remove the element from the list if it returns true.

I know how to iterate:

    for (Iterator i = bombGrid.listIterator(); i.hasNext();) {
    if () {         
        i.remove();
}

But I've no idea how to access the method isExploded of the Bomb class itself via the iterator. Does anyone know the answer to this?

Sincerely,

Luxo

Upvotes: 2

Views: 5964

Answers (3)

Arne Burmeister
Arne Burmeister

Reputation: 20614

If you use Java 5, use generics:

List<Bomb> bombGrid = ...;
for (Iterator<Bomb> i = bombGrid.iterator(); i.hasNext();) {
  if (i.next().isExploded()) {         
    i.remove();
  }
}

Upvotes: 0

user1898956
user1898956

Reputation: 46

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

Upvotes: -2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382454

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.

Upvotes: 5

Related Questions