迭代时修改Java ArrayList

Dan*_*ats 5 java iterator

我想要做类似的东西 这个

但是,我不希望迭代添加的元素.基本上我有一个底层的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
}
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*has 5

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