As in the previous post we have explained how to iterate over the collection. the same code can be found by clicking on the below mentioned link. Now here the same piece of code will be used to explain the modification of collection at the time of iteration. Now new hotel is declared and when it is added at the time of iteration, it has thrown the below mentioned error in the console:-
The error is “CocurrentModificationException”:-
This error is thrown as inside the loop of iteration we are trying to change the collection that we are iterating. One approach is, the element that we want to add, add that in a separate collection as mentioned below.
Here one new collection is created add added that hotel outside of the for each loop.