2009-04-09 95 views
13

以下代碼給我一個NullPointerException。問題是以下行:使用HashMap的put方法時的NullPointerException

... 
dataMap.put(nextLine[0], nextLine[6]); 

奇怪的是,我已經沒有上述線路和呼叫nextLine[0]nextLine[6]工作完全按預期運行這段代碼 - 這是他們給我回一個元素csv文件。我聲明並初始化HashMap的代碼早些時候方法

String[] nextLine; 
    int counter=0; 
    while (counter<40) { 
    counter++; 

    System.out.println(counter); 
    nextLine = reader.readNext(); 
    // nextLine[] is an array of values from the line 
    System.out.println(nextLine[0] + " - " + nextLine[6] +" - " + "etc..."); 
    dataMap.put(nextLine[0], nextLine[6]); 
    } 
    return dataMap; 
} 

回答

26
HashMap<String, String> dataMap = new HashMap<String,String>(); 

您的dataMap變量在此處未初始化。你應該得到一個編譯器的警告。

+0

這個問題真的沒有明確地初始化嗎?爲空? – 2009-04-09 16:13:42

+0

我認爲Codingscape的意思是說「沒有實例化」 – 2009-04-09 17:34:52

5

HashMap<String, String> dataMap = null; 

的數據圖初始化?它始終爲空。

爲了澄清,您聲明該變量並將其設置爲null。但是你需要實例化一個新的Map,不管它是一個HashMap還是類似的。

例如

datamap = new HashMap(); 

(撇開仿製藥等)

+0

是的,很明顯,取消引用顯式爲null的指針會引發NullPointerException。 – Apocalisp 2009-04-09 16:06:09

3

的數據圖的已宣告但尚未初始化。它可以初始化爲

datamap = new HashMap();

1

那麼,有三個對象訪問該行。如果nextLine [0]和nextLine [6]不爲null,因爲上面的println調用起作用,那麼就會留下dataMap。你做了dataMap = new HashMap(); somwehere?

0

嗯,究竟是什麼你期望當你這樣做?

HashMap<String, String> dataMap = null; 
... 
dataMap.put(...)