So I have this loop in my code that needs two separately working Iterators. However, when it tries to use rbIterator.next(), java throws a ConcurrentModificationException. How do I stop that from happening?
Thanks
Iterator<Road> raIterator = roads.listIterator(0); //I also tried .iterator(), with no avail
while(raIterator.hasNext()){
Road ra = raIterator.next();
Iterator<Road> rbIterator = roads.listIterator(0);
while(rbIterator.hasNext()){
Road rb = rbIterator.next();
//snipped code that adds a road to the list
roads.add(xyz);
}
}
You can’t add items to most standard implementations of
Listwhile iterating over them, unless you create an implementation that allows it!ArrayListdoes not, however, see javadoc. Nor do most* (perhaps all) of the Java Collections FrameworksListimplementations.A solution would be to create a new list,
temp, before iterating, add elements totempwhile you iterate, and then add all of the elements intempto the first.Edit: used
addAll(temp), thanks @Michael Easter