Changing Java ArrayList while iterating over it

I want to do something like this

However, I do NOT want the added elements to be repeated. Basically I have a basic arraylist and I am returning an iterator over an arraylist. Repeating the use of this iterator, I want to add elements to the original arraylist. How to do it?

EDIT: The problem is that I need objects in the iterator modified by the iterative code. I don't think that cloning an arraylist would 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 now the card is 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);
}
+5
source share
2 answers

You can 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 be trying out new itens.

+5

.

ArraList<E> a = new ArrayList<E>();
Iteratore<E> i = a.iterator();
loop(check condition){
    if(satisfied){
         a.add(E e);
    }
}
0

All Articles