I wanted to not make a copy of the set in the removeAllNumbersGreaterThan10 and do the method on the same set given to it. but it returns these errors: Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1584) at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1607) at com.codegym.justCoding.Main.removeAllNumbersGreaterThan10(Main.java:16) at com.codegym.justCoding.Main.createSet(Main.java:12) at com.codegym.justCoding.Main.main(Main.java:24)
Why is the copy necessary?
You must be signed in to leave a comment
9 September 2021, 19:39
It is illegal to continue to iterate (such as a foreach loop or an Iterator) over a set after removing an item from that set. That means that you can remove an item, however if the loop does not exit thereafter and continues into a new loop cycle then an exception is thrown. Creating a copy allows you to loop over the copy while removing items from the original, which does not break the above rule. This task does not require you to do it that way but you will need to ensure that your solve does not break this rule.
12 September 2021, 12:01
Thank you so much. Didn't know about that rule,is that something I should've learned by now or it's meant to be learned in the future?
13 September 2021, 14:05
I didn't know it myself until I was doing the same set of tasks you are on. I don't know if the lessons skipped over that fact or if I just didn't understand what the lessons were saying until I started writing error prone code. I'll admit that the latter was true for myself more often than not. Don't get discouraged if you find this happening to you too, I personally believe the best way to learn code is by making mistakes. A little frustration sticks with you. I also read Java books outside this course and don't fully understand the lessons until I get out there with code and start making mistakes. At that point things start making sense between what I have read and the actual practical usage. Check out my forum post on some good programming videos on Youtube. They are not all Java specific. The very first one I recommend to nearly everyone. It is a college lecture of day 1 of a beginners programming class. The speaker talks a lot about what to expect and even says that learning to code involves LOTS of errors. He has a lot of good advice about managed expectations.