I know if would be trying to remove from collection looping through it with the simple loop I will be getting this exception: java.util.ConcurrentModificationException
. But I am using Iterator and it still generates me this exception. Any idea why and how to solve it?
HashSet<TableRecord> tableRecords = new HashSet<>(); ... for (Iterator<TableRecord> iterator = tableRecords.iterator(); iterator.hasNext(); ) { TableRecord record = iterator.next(); if (record.getDependency() == null) { for (Iterator<TableRecord> dependencyIt = tableRecords.iterator(); dependencyIt.hasNext(); ) { TableRecord dependency = dependencyIt.next(); //Here is the line which throws this exception if (dependency.getDependency() != null && dependency.getDependency().getId().equals(record.getId())) { tableRecords.remove(record); } } } }
ConcurrentModificationException is not thrown by Iterator. remove() because that is the permitted way to modify an collection while iterating. This is what the javadoc for Iterator says: Removes from the underlying collection the last element returned by this iterator (optional operation).
How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.
The java. util. concurrentmodificationexception is an error in Java. The error occurs when the iterator is traversing a list, and a command is used to change an element's value during that traversal.
You must use iterator.remove()
instead of tableRecords.remove()
You can remove items on a list on which you iterate only if you use the remove method from the iterator.
EDIT :
When you create an iterator, it starts to count the modifications that were applied on the collection. If the iterator detects that some modifications were made without using its method (or using another iterator on the same collection), it cannot guarantee anymore that it will not pass twice on the same element or skip one, so it throws this exception
It means that you need to change your code so that you only remove items via iterator.remove (and with only one iterator)
OR
make a list of items to remove then remove them after you finished iterating.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With