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);
}
2
  • 1
    it would be helpful if you provided the relevant code Commented Feb 11, 2012 at 2:45
  • Added code. Sorry for omitting it. Commented Feb 11, 2012 at 22:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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,
This is probably the clean and safest way to handle the member of an arraylist while iterating. I used this technique and seen consistency
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);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.