我有此HashMap如何從HashMap中刪除密鑰?
HashMap <Integer,Integer> H = new HashMap <Integer,Integer>();
,當我嘗試刪除從HashMap中的關鍵我recive這個錯誤
**Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:922)
at java.util.HashMap$KeyIterator.next(HashMap.java:956)
at Livre.montantTotal(Livre.java:42)**
這是我的代碼
for (int e : H.keySet()){
H.put(e, H.get(e)-1);
if (H.get(e) == 0){
H.remove(e);
}
}
您在遍歷整個集合時無法修改集合。 –
好吧,您可以在Iterator上使用remove()方法(因此將for循環展開成適當的Iterator),但是當您迭代它時,您將無法添加到集合中。也許收集列表中的新增內容並在最後添加它們。 – slipperyseal
@FernandoMatsumoto嗯,它是相關的,但並不真正重複,因爲這裏是一張地圖 – Dici