在迭代它时修改Java ArrayList [英] Modifying Java ArrayList while iterating over it

查看:179
本文介绍了在迭代它时修改Java ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似
的事情

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

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?

编辑:这个问题是我需要迭代代码修改的迭代器中的对象。我不认为克隆arraylist会起作用...

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


推荐答案

您可以创建列表的副本并迭代副本并将数据添加到旧副本。问题是您不会迭代新的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.

这篇关于在迭代它时修改Java ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆