Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying Java ArrayList while iterating over it

Tags:

java

iterator

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);
}
like image 567
Daniel Kats Avatar asked Feb 11 '12 02:02

Daniel Kats


People also ask

Can we modify ArrayList while iterating?

ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.

Can we update the list while iterating in Java?

Iterating using Iterator/ListIterator allows to add/remove element and these modification (add/remove) is reflected in the original List.

Can you modify a Collection while iterating?

It is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.

How do you modify an ArrayList in Java?

To update or replace the existing value with the new value of ArrayList, use set(int index, E element) with the index and new value. From the output, we can see that index 3 value 40 is removed from the list and updated with the new value 333. After replacing the index 3 value, the list size is unchanged.


1 Answers

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.

like image 187
Mikhas Avatar answered Sep 22 '22 23:09

Mikhas