簡體   English   中英

使用 HashMap 的 put 方法時出現 NullPointerException

[英]NullPointerException while using put method of HashMap

下面的代碼給了我一個NullPointerException 問題出在以下幾行:

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

奇怪的是,我在沒有上面一行的情況下運行了這段代碼,並且對nextLine[0]nextLine[6]的調用完全按預期工作——也就是說,它們給了我一個 csv 文件的元素。 我用代碼聲明並初始化了HashMap

HashMap<String, String> dataMap = null;

在方法的前面

  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;
}
HashMap<String, String> dataMap = new HashMap<String,String>();

您的dataMap變量此時尚未初始化。 您應該收到有關此的編譯器警告。

數據映射在哪里初始化? 它始終為空。

為了澄清起見,您聲明了變量並將其設置為 null。 但是你需要實例化一個新的 Map,無論是 HashMap 還是類似的。

例如

datamap = new HashMap();

(拋開泛型等)

dataMap 已聲明但未初始化。 它可以初始化為

數據映射 = 新 HashMap();

那么,在該行上訪問了三個對象。 如果 nextLine[0] 和 nextLine[6] 不為 null,因為上面的 println 調用有效,那么就剩下 dataMap。 你做了 dataMap = new HashMap(); 某處?

我的情況與通常情況不同,當嘗試讀取不存在的鍵時,哈希圖會拋出空指針異常,例如我有一個

HashMap<String, Integer> map = new HashMap<String, Integer>();

哪個是空的或有除“someKey”之外的鍵,所以當我嘗試

map.get("someKey") == 0;

現在,由於將 null 與某個整數匹配,這將產生 nullPointerExeption。

我應該怎么做?

Ans:我應該檢查 null like

map.get("someKey") != null;

現在運行時錯誤 Nullpointer 不會引發!

嗯,能指望什么,當你做到這一點?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM