有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java删除arraylist迭代器

我有一个Java的ArrayList,属于我的“Bomb”类

这个类有一个方法“IsExploed”,如果炸弹爆炸,这个方法将返回true,否则返回false

现在我尝试遍历这个arraylist,调用这个方法ISExploed,如果返回true,则从列表中删除元素

我知道如何迭代:

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

但我不知道如何通过迭代器访问Bomb类本身的isexplod方法。有人知道答案吗

真诚地

卢克索


共 (3) 个答案

  1. # 1 楼答案

    如果使用Java 5,请使用泛型:

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

    你需要使用next获得炸弹:

    for (Iterator i = bombGrid.listIterator(); i.hasNext();) {
       Bomb bomb = (Bomb) i.next(); 
       if (bomb.isExploded()) i.remove();
    }
    

    或者,如果您可以从bombGrid中获得一个Iterator<Bomb>(是一个ArrayList<Bomb>):

    Iterator<Bomb> i = bombGrid.listIterator();
    while (i.hasNext()) {
       Bomb bomb = i.next(); 
       if (bomb.isExploded()) i.remove();
    }
    

    这假设您的迭代器支持remove,例如ArrayList给出的迭代器就是这种情况

  3. # 3 楼答案

    不可以,在ArrayList的迭代器中进行迭代时,不能删除它。以下是Javadoc摘录:

    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