2
这是我的HashMap:如何用LinkedList更新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);
的问题是关系到链表和初始化。有没有办法避免这个问题?
编辑:完整的代码。
//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(关键);总是返回值?只需调试程序或添加一个System.out.println并获取分区的地图值(key) –
好吧,我得到了错误。它总是返回null,但这是因为我需要获取密钥本身,而不是在init步骤中的值全为空。 – user840718