java.util.ConcurrentModificationException z iteratorem
Wiem, że jeśli próbowałbym usunąć z kolekcji pętlę poprzez prostą pętlę, otrzymam ten wyjątek:java.util.ConcurrentModificationException
. Ale używam Iteratora i nadal generuje ten wyjątek. Jakiś pomysł dlaczego i jak go rozwiązać?
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);
}
}
}
}