Как перебрать HashMap, избегая ConcurrentModificationException - PullRequest
1 голос
/ 12 марта 2012

У меня есть 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, но мне нужна точно такая же функциональность.

Ответы [ 2 ]

7 голосов
/ 12 марта 2012

Может не решить вашу проблему полностью, но вместо innerHashMap.remove(innerEnt.getKey()); вам нужно использовать метод удаления итератора innerIterator.remove();

2 голосов
/ 12 марта 2012

Вы пытались использовать Synchronized Hashmap? Collections.synchronizedMap(new HashMap()) или взгляните на ConcurrentHashMap

...