繁体   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