gpt4 book ai didi

java - 在迭代时修改 Java ArrayList

转载 作者:搜寻专家 更新时间:2023-10-31 20:05:25 26 4
gpt4 key购买 nike

我想做类似的事情 this

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

编辑:这个问题是我需要迭代代码修改迭代器中的对象。我不认为克隆 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
}

这是在另一个类中使用的 map 。

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);
}

最佳答案

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

关于java - 在迭代时修改 Java ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9237384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com