【问题标题】:How to update values in HashMap with LinkedList?如何使用 LinkedList 更新 HashMap 中的值?
【发布时间】:2016-11-13 12:18:47
【问题描述】:

这是我的 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());
        }
    }
}

【问题讨论】:

  • 发布完整代码,因为提到的变量缺少声明
  • 是 partitionMap.get(key);总是返回值?只需调试程序或添加 System.out.println 并获取 partitionMap.get(key) 的值
  • 好的,我得到了错误。它总是返回 null,但那是因为我需要获取密钥本身,而不是 init 步骤中全部为 null 的值。
  • 干得好,大多数时候调试代码都能解决问题:)

标签: java nullpointerexception linked-list hashmap


【解决方案1】:

尝试在 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"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多