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);
}
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.
Iterating using Iterator/ListIterator allows to add/remove element and these modification (add/remove) is reflected in the original List.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With