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