【发布时间】:2012-03-03 11:44:26
【问题描述】:
我想做类似的事情 this
但是,我不希望添加的元素被迭代。基本上我有一个底层的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);
}
【问题讨论】:
-
提供相关代码会很有帮助
-
添加了代码。抱歉省略了。