Java 使用 HashMap 的 put 方法时出现 NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/734861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:50:39  来源:igfitidea点击:

NullPointerException while using put method of HashMap

javahashmapnullpointerexception

提问by Ankur

The following code is giving me a NullPointerException. The problem is on the following line:

下面的代码给了我一个NullPointerException. 问题出在以下几行:

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

What is strange is that I have run this code without the above line and the call to nextLine[0]and nextLine[6]work exactly as expected - that is they give me back elements of a csv file. I declare and initialise the HashMapwith the code

奇怪的是,我在没有上面一行的情况下运行了这段代码,并且调用nextLine[0]nextLine[6]完全按预期工作——也就是说,它们给了我一个 csv 文件的元素。我HashMap用代码声明并初始化

HashMap<String, String> dataMap = null;

earlier in the method

在方法的前面

  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;
}

采纳答案by Codingscape

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

Your dataMapvariable isn't initialized at this point. You should be getting a compiler warning about that.

此时您的dataMap变量尚未初始化。您应该收到有关此的编译器警告。

回答by Brian Agnew

Where is datamap initialised ? It's always null.

数据映射在哪里初始化?它始终为空。

To clarify, you declare the variable and set it to null. But you need to instantiate a new Map, whether it's a HashMap or similar.

为了澄清起见,您声明了变量并将其设置为 null。但是你需要实例化一个新的 Map,无论是 HashMap 还是类似的。

e.g.

例如

datamap = new HashMap();

(leaving aside generics etc.)

(抛开泛型等)

回答by Sheldon

dataMap is declared but not initialized. It can be initialized with

dataMap 已声明但未初始化。它可以初始化为

datamap = new HashMap();

数据映射 = 新 HashMap();

回答by jcopenha

Well, there are three objects accessed on that line. If nextLine[0] and nextLine[6] aren't null, because the println call above worked, then that leaves dataMap. Did you do dataMap = new HashMap(); somwehere?

那么,在该行上访问了三个对象。如果 nextLine[0] 和 nextLine[6] 不为 null,因为上面的 println 调用有效,那么就剩下 dataMap。你做了 dataMap = new HashMap(); 某处?

回答by Michael Borgwardt

Um, what exactly doyou expect when you do this?

嗯,什么你期望,当你做到这一点?

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