提问人:Ankur 提问时间:4/10/2009 最后编辑:EddieAnkur 更新时间:2/10/2021 访问量:53852
使用 HashMap 的 put 方法时出现 NullPointerException
NullPointerException while using put method of HashMap
问:
下面的代码给了我一个.问题出在以下行:NullPointerException
...
dataMap.put(nextLine[0], nextLine[6]);
奇怪的是,我在没有上述行的情况下运行了这段代码,并且完全按照预期工作 - 也就是说,它们给了我 csv 文件的元素。我声明并用代码初始化nextLine[0]
nextLine[6]
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;
}
答:
数据映射在哪里初始化?它始终为 null。
为了清楚起见,请声明变量并将其设置为 null。但是你需要实例化一个新的 Map,无论是 HashMap 还是类似的。
例如
datamap = new HashMap();
(撇开泛型等)
评论
dataMap 已声明,但未初始化。它可以用
数据映射 = new HashMap();
嗯,在那条线上有三个对象被访问。如果 nextLine[0] 和 nextLine[6] 不为 null,因为上面的 println 调用有效,那么剩下的就是 dataMap。你做了吗 dataMap = new HashMap();索姆韦赫?
HashMap<String, String> dataMap = new HashMap<String,String>();
此时变量尚未初始化。您应该收到有关此的编译器警告。dataMap
评论
嗯,当你这样做时,你到底期望什么?
HashMap<String, String> dataMap = null;
...
dataMap.put(...)
评论
我的情况与通常不同,哈希图在尝试读取不存在的键时会抛出空指针异常,例如我有一个
HashMap<String, Integer> map = new HashMap<String, Integer>();
哪个是空的或除了“someKey”之外有键,所以当我尝试
map.get("someKey") == 0;
现在,由于将 null 与某个整数匹配,这将产生一个 nullPointerExeption。
我该怎么办?
答:我应该检查null like
map.get("someKey") != null;
现在运行时错误 Nullpointer 不会引发!
上一个:VB 代码中奇怪的空指针异常
下一个:空指针异常 JLabel
评论