問題描述
我知道是否會嘗試通過簡單的循環(huán)從集合中刪除,我會得到這個異常:java.util.ConcurrentModificationException
.但我正在使用迭代器,它仍然會產(chǎn)生這個異常.知道為什么以及如何解決它嗎?
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);
}
}
}
}
推薦答案
你必須使用 iterator.remove()
而不是 tableRecords.remove()
You must use iterator.remove()
instead of tableRecords.remove()
只有在迭代器中使用 remove 方法時,才能刪除要迭代的列表中的項目.
You can remove items on a list on which you iterate only if you use the remove method from the iterator.
當(dāng)您創(chuàng)建迭代器時,它會開始計算應(yīng)用于集合的修改.如果迭代器檢測到一些修改沒有使用它的方法(或者在同一個集合上使用另一個迭代器),它不能再保證它不會在同一個元素上傳遞兩次或跳過一個,所以它拋出這個異常
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
這意味著您需要更改代碼,以便僅通過 iterator.remove 刪除項目(并且只有一個迭代器)
It means that you need to change your code so that you only remove items via iterator.remove (and with only one iterator)
或
列出要刪除的項目,然后在完成迭代后將其刪除.
make a list of items to remove then remove them after you finished iterating.
這篇關(guān)于帶有迭代器的 java.util.ConcurrentModificationException的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!