在迭代 Java ArrayList 时修改它
我想做类似的事情 这个
但是,我不希望添加的元素迭代了一遍。基本上我有一个底层数组列表,并且我在数组列表上返回一个迭代器。在使用该迭代器进行迭代时,我想将元素添加到原始数组列表中。我该怎么做?
编辑:问题是我需要迭代器中的对象由迭代代码修改。我不认为克隆 arraylist 会起作用...
编辑2:这是我的代码的精简版本。
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);
}
I want to do something similar to
this
However, I do NOT want the added elements to be iterated over. Basically I have an underlying arraylist, and I return an iterator over the arraylist. While iterating using that iterator, I want to add elements to the original arraylist. How do I do this?
EDIT: The problem with this is that I need the objects in the iterator modified by the iterating code. I don't think that cloning the arraylist will work...
EDIT2: Here is a stripped-down version of my code.
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
}
And here is the map being used in another class.
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建列表的副本并迭代该副本并向旧列表添加数据。问题是您不会迭代新的 itens。
You may create a copy of your list and iterate over the copy and add data to the old one. The problem is that you will not iterate over the new itens.
它可能对你有帮助。
It may hep you.