Java – double iterator loop
•
Java
So I have this loop in my code that requires two separate iterators But when it tries to use rbitterer When next(), Java will throw concurrentmodificationexception How can I prevent this from happening?
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); } }
Solution
Unless you create an implementation that allows it, you cannot add items to most standard implementations of list when iterating over them!
However, ArrayList will not see Javadoc Most * (possibly all) Java Collections Framework list implementations will not
The solution is to create a new list temp before the iteration, add the elements to temp during the iteration, and then add all the elements in temp to the first one
Editor: use addall (Temp), thanks @ Michael Easter
List<Road> temp = new ArrayList<Road>(); for(Road ra : roads){ for (Road rb : roads){ temp.add(xyz); } } roads.addAll(temp);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码