Wiem że da się zrobić to zadanie bez użycia Iterator. Ale twórca kursu mówiąc o Iterator chciał żebym się go nauczył. Dlatego chciałbym żeby mi ktoś wytłumaczył jak w tym zadaniu użyć Iterator. Napiszę jeszcze raz proszę o pomoc jak użyć Iterator.
It is an illegal operation to continue iterating over a collection that has been modified without the Iterator's own remove() method while iterating. Be aware that the modification is not the illegal part that will crash the code, it is when you try to move to the next iteration cycle after modification that the Exception occurs. Take, for example, a bit of code that has a List of Strings and you want to remove a specific String if it is contained in the List. You could Iterate through the list and see if the value you want to remove is contained. If you remove it without using the Iterator's remove() method and then the Iterator continues you will end up with an Exception being thrown. See this example coded below:
If the next() method is never called after an illegal modification, the code will not crash. Here is the same code but has one extra line that prevents the Exception:
In this code, when an illegal modification is made, there is a "break" that ends the loop that the Iterator is using. Therefore the next() method is not called after an illegal modification occurs and the code is safe.
And finally, you can remove items from a Collection you are iterating over AS LONG AS you use the Iterator's own remove() method. See the same code again this time using the iterator's remove():
You don't require a "break" after an item has been removed because the Iterator's own remove() method is safe and the code runs without crashing.
P.S.
- Any modification that adds or removes items over a collection being iterated over is illegal. The code that you shared is both adding and removing items.
- foreach loops use an Iterator in the background to go over each item in a Collection. You are not able to access this Iterator. Therefore there is no safe method like the Iterator's remove() method that can be used in foreach loops. ANY modification (where the loop continues) will crash that code.
0
This website uses cookies to provide you with personalized service. By using this website, you agree to our use of cookies. If you require more details, please read our Terms and Policy.