Possible Duplicates:
Java: Efficient Equivalent to Removing while Iterating a Collection
Removing items from a collection in java while iterating over itJak mogę iterować nad obiektem podczas modyfikowania go w Javie?
Próbuję pętli HashMap
:
Map<String, Integer> group0 = new HashMap<String, Integer>();
... i wyodrębnić każdy element w group0
. To jest moje podejście:
// iterate through all Members in group 0 that have not been assigned yet
for (Map.Entry<String, Integer> entry : group0.entrySet()) {
// determine where to assign 'entry'
iEntryGroup = hasBeenAccusedByGroup(entry.getKey());
if (iEntryGroup == 1) {
assign(entry.getKey(), entry.getValue(), 2);
} else {
assign(entry.getKey(), entry.getValue(), 1);
}
}
Problemem jest to, że każde wywołanie assign()
usunie elementy z group0
, modyfikując w ten sposób swój rozmiar, powodując następujący błąd:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$EntryIterator.next(HashMap.java:834)
at java.util.HashMap$EntryIterator.next(HashMap.java:832)
at liarliar$Bipartite.bipartition(liarliar.java:463)
at liarliar$Bipartite.readFile(liarliar.java:216)
at liarliar.main(liarliar.java:483)
Więc ... jak czy mogę przełączać się między elementami w group0
podczas dynamicznej zmiany?
Wykonaj kopię mapy group0 i usuń elementy z kopii podczas przechodzenia przez grupę0? – sarahTheButterFly
@sarah ... dobry punkt. Spróbuję tego. – Hristo
@sarah ...kopiowanie grupy0 do klonu HashMap daje mi problem, że kiedy usuwam z grupy0, również usuwam z klonu. Jak mogę to pokonać? Jak utworzyć niezależną kopię grupy0? – Hristo