如何使用LinkedList更新HashMap中的值



这是我的HashMap:

public static HashMap<String, LinkedList<LinkedList<String>>> partitionMap;
partitionMap = new HashMap<String, LinkedList<LinkedList<String>>>();

我的程序有一个初始化的初始步骤,其中添加了所有的键,没有值。之后,我需要检索键并添加值。问题是,即使我初始化LinkedList,我也得到了空指针异常。

初始化步骤:

LinkedList<LinkedList<String>> ll = new LinkedList<LinkedList<String>>();
partitionMap.put(key, ll);
之后

:

LinkedList<LinkedList<String>> l = partitionMap.get(key);
l.add(partition);  //CRASH, null pointer exception
partitionMap.put(key, l);

问题与LinkedList及其初始化有关。有办法避免这个问题吗?

编辑:完整代码。

   //This function is called N time to fill the partitionMap with only keys
   public void init(DLRParser.SignatureContext ctx) {
    LinkedList<LinkedList<String>> l = new LinkedList<LinkedList<String>>();
    partitionMap.put(ctx.getText(), l);
}
  //After that, this function is called to fill partitionMap with only values
public void processing(DLRParser.MultiProjectionContext ctx) {  
    LinkedList<String> partition = new LinkedList<String>();
    for (TerminalNode terminalNode : ctx.U()) {
        partition.add(terminalNode.getText());
    }
    Collections.reverse(partition);
    //iteration on another HashMap with the same keys, if we have a match
    //then add the values to the partitionMap
    for(Entry<String, LinkedList<String>> entry : tableMap.entrySet())
    {
        String key = entry.getKey();
        LinkedList<String> attributes = entry.getValue();
        if(attributes.containsAll(partition)) //match
        {
            //retrieve the LinkedList of LinkedList with value
            LinkedList<LinkedList<String>> l = partitionMap.get(key);
            l.add(partition); // CRASH - Nullpointer exception
            partitionMap.put(key, l); //add it -
            System.out.println(l.toString());
        }
    }
}

尝试在java8中添加putIfAbsent方法来初始化使用默认值的List

    HashMap<String, List<List<String>>> partitionMap = new HashMap<String, List<List<String>>>();
    partitionMap.putIfAbsent("a", new LinkedList<>(new LinkedList<>()));
    partitionMap.get("a").add(Arrays.asList("b"));

相关内容

  • 没有找到相关文章

最新更新