[英]How to iterate over a HashMap while avoiding ConcurrentModificationException
我有一個HashMap,其類型為HashMap<String,HashMap<String,int>>
現在我需要遍歷此HashMap並刪除任何鍵的值為0的內部HashMap。
如果這樣的移除使內部HashMap為空,則內部HashMap的對應鍵將從外部HashMap中移除。 我嘗試對其進行迭代,然后刪除符合要求的元素,但這引發了ConcurrentModificationException
。
我嘗試了以下代碼:
synchronized(MyConstants.cliListUpdateList)
{
synchronized(MyConstants.cliList)
{
outerEntries = MyConstants.cliListUpdateList.entrySet();
outerIterator = outerEntries.iterator();
while(outerIterator.hasNext())
{
outerEnt = (Entry) outerIterator.next();
innerHashMap = (HashMap) outerEnt.getValue();
synchronized(innerHashMap)
{//synchronize innerhashmap
innerEntries = innerHashMap.entrySet();
innerIterator = innerEntries.iterator();
synchronized(innerIterator)
{
while(innerIterator.hasNext())
{
innerEnt = (Entry) innerIterator.next();
int k = Integer.parseInt((String)innerEnt.getValue());
if(k==0)
{
innerHashMap.remove(innerEnt.getKey());
if(innerHashMap.isEmpty())
{
MyConstants.cliListUpdateList.remove(outerEnt.getKey());
}
ArrayList ports = (ArrayList) MyConstants.cliList.get(outerEnt.getKey());
ports.remove((String)innerEnt.getKey());
if(ports.isEmpty())
{
MyConstants.cliList.remove(outerEnt.getKey());
}
}
else
{
k--;
innerHashMap.put(innerEnt.getKey(), k+"");
MyConstants.cliListUpdateList.put(outerEnt.getKey(), innerHashMap);
}
}
}
}//synchronize innerhashmap
}
System.out.println(MyConstants.cliListUpdateList + " <---> "+ MyConstants.cliList);
}
}
我在這一行收到異常: innerEnt = (Entry) innerIterator.next();
。 我嘗試了Iterator類提供的remove方法。 但這也不是一件好事。
編輯
從Java文檔中我很了解, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this(ConcurrentModificationException) exception
但我需要完全相同的功能。
可能無法完全解決您的問題,而不是innerHashMap.remove(innerEnt.getKey());
您需要使用迭代器的remove方法innerIterator.remove();
您是否嘗試過使用同步哈希圖? Collections.synchronizedMap(new HashMap())
或看看ConcurrentHashMap
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.