5

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);
}
Community
  • 1
  • 1
Daniel Kats
  • 5,141
  • 15
  • 65
  • 102

2 Answers2

5

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.

Mikhas
  • 851
  • 1
  • 12
  • 31
  • bit more work, but you could keep a variable that goes from true to false, when there are no changes, f.e. while(Changes) => make a copy, set changes to false, do the process, if something gets added or changed, you change it to true, else the process will end, – Jonathan Feb 11 '12 at 02:50
  • This is probably the clean and safest way to handle the member of an arraylist while iterating. I used this technique and seen consistency – Steer360 Mar 15 '13 at 11:59
0

It may hep you.

ArraList<E> a = new ArrayList<E>();
Iteratore<E> i = a.iterator();
loop(check condition){
    if(satisfied){
         a.add(E e);
    }
}
Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125