我想要做同樣的事情到 this修改Java的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);
}
如果您提供相關代碼 – ggreiner 2012-02-11 02:45:06
添加的代碼將會很有幫助。對不起,省略它。 – BlackSheep 2012-02-11 22:20:41