У меня есть HashMap, его тип HashMap<String,HashMap<String,int>>
Теперь мне нужно перебрать этот HashMap и удалить внутренние HashMaps со значением 0 для любого ключа.
Если такое удаление делает внутренний 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. Но это тоже нехорошо.
EDIT
из документации по 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
, но мне нужна точно такая же функциональность.