我想做类似的事情this https://stackoverflow.com/questions/993025/java-adding-elements-to-a-collection-during-iteration
但是,我不希望迭代添加的元素。基本上我有一个底层数组列表,并且我在数组列表上返回一个迭代器。在使用该迭代器进行迭代时,我想将元素添加到原始数组列表中。我该怎么做呢?
编辑:问题是我需要迭代器中的对象由迭代代码修改。我不认为克隆数组列表会起作用......
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);
}
您可以创建列表的副本并迭代该副本并向旧列表添加数据。问题是您不会迭代新的 itens。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)