迭代时修改Java ArrayList

时间:2012-02-11 02:42:14

标签: java iterator

我想做类似的事情 this

但是,我不希望迭代添加的元素。基本上我有一个底层的arraylist,我在arraylist上返回一个迭代器。在使用该迭代器进行迭代时,我想将元素添加到原始的arraylist中。我该怎么做?

编辑:这个问题是我需要迭代代码修改的迭代器中的对象。我不认为克隆arraylist会起作用......

EDIT2:这是我的代码的精简版。

public class Map {
     // a bunch of code
     private ArrayList<Robot> robots;

     public Iterator<Robot> getRobots() {
          return robots.iterator();
     }

     public void buildNewRobot(params) {
          if(bunchOfConditions)
                robots.add(new Robot(otherParams);
     }

     // a bunch more code
}

这是另一个类中使用的地图。

for(Iterator<Robot> it = map.iterator(); it.hasNext();){
   Robot r = it.next();
   // a bunch of stuff here
   // some of this code modifies Robot r 

   if(condition)
       map.buildNewRobot(params);
}

2 个答案:

答案 0 :(得分:5)

您可以创建列表的副本并迭代副本并将数据添加到旧副本。问题是你不会迭代新的itens。

答案 1 :(得分:0)

它可能对你有帮助。

ArraList<E> a = new ArrayList<E>();
Iteratore<E> i = a.iterator();
loop(check condition){
    if(satisfied){
         a.add(E e);
    }
}