Possible Duplicates:
Java: Efficient Equivalent to Removing while Iterating a Collection
Removing items from a collection in java while iterating over itLàm thế nào tôi có thể lặp qua một đối tượng trong khi sửa đổi nó trong Java?
Tôi đang cố gắng để lặp qua HashMap
:
Map<String, Integer> group0 = new HashMap<String, Integer>();
... và trích xuất tất cả các phần tử trong group0
. Đây là cách tiếp cận của tôi:
// 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);
}
}
Vấn đề ở đây là mỗi cuộc gọi đến assign()
sẽ loại bỏ các yếu tố từ group0
, do đó thay đổi kích thước của nó, do đó gây ra lỗi sau:
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)
Vì vậy, ... làm thế nào tôi có thể lặp qua các phần tử trong group0
trong khi nó tự động thay đổi không?
Tạo bản sao của bản đồ nhóm0 và xóa các phần tử khỏi bản sao trong khi lặp qua nhóm0? – sarahTheButterFly
@ sarah ... điểm tốt. Tôi sẽ thử xem. – Hristo
@sarah ...sao chép trên group0 đến một HashMap bản sao cho tôi vấn đề mà khi tôi loại bỏ từ group0, tôi cũng loại bỏ từ bản sao. Làm thế nào tôi có thể vượt qua điều đó? Làm cách nào để tạo một bản sao độc lập của nhóm0? – Hristo