在不添加新条目的情况下更新HashMap

时间:2016-11-14 13:03:11

标签: java hashmap

我的程序使用两个HashmMap,它们具有完全相同的条目数和相同的键。 一个(tableMap)是静态的,永远不会改变。另一个是动态(partitionMap),这意味着我需要更新值。 我的算法遇到了一个问题,因为当它应该不是时,似乎又增加了一个条目。

//I have a LinkedList of strings that I want to add to the HashMap partitionMap
LinkedList<String> partition = new LinkedList<String>();
    for (TerminalNode terminalNode : ctx.U()) {
        partition.add(terminalNode.getText());
    }     
//for each entry of tableMap
for(Entry<String, LinkedList<String>> entry : tableMap.entrySet())
    {
        //I retrieve keys and values from tableMap
        String key = entry.getKey();
        LinkedList<String> attributes = entry.getValue();

        //the condition: if my linkedlist is included in the other do...
        if(attributes.containsAll(partition))
        {
            //get the list of values
            ArrayList<LinkedList<String>> l = partitionMap.get(key);
            //but the first time is always null since I init partitionMap without values
            if(l==null)
            {
                ArrayList<LinkedList<String>> firstLL = new ArrayList<LinkedList<String>>();
                firstLL.add(partition);
                partitionMap.put(key, firstLL); //BUG HERE! add one more entry instead of just updating values
            }
            else
            {
                l.add(partition);
                partitionMap.put(key, l);
            }
        }
    }

有人知道为什么这是错的吗?

0 个答案:

没有答案