Java delete arraylist iterator

后端 未结 3 587
借酒劲吻你
借酒劲吻你 2020-12-20 00:22

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.

相关标签:
3条回答
  • 2020-12-20 01:04

    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

    0 讨论(0)
  • 2020-12-20 01:05

    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.

    0 讨论(0)
  • 2020-12-20 01:14

    If you use Java 5, use generics:

    List<Bomb> bombGrid = ...;
    for (Iterator<Bomb> i = bombGrid.iterator(); i.hasNext();) {
      if (i.next().isExploded()) {         
        i.remove();
      }
    }
    
    0 讨论(0)
提交回复
热议问题