gpt4 book ai didi

java - 将 linkedhashmap 中的信息写入文件时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 17:17:33 25 4
gpt4 key购买 nike

我正在尝试将信息从 LinkedHashmap 写入文件,但此代码给了我一个 NullPointerException:

public void writeFile(String file, Map<Word, Defination> wmap) {

File FileName = new File(file);
try {

FileOutputStream stream = new FileOutputStream(FileName, true);
PrintStream pstrim = new PrintStream(stream);
String line = null;
rmap=wmap;
Iterator<Word> it = wmap.keySet().iterator(); //generic iterator
while (it.hasNext() && found == 0) {
String key = it.next().getWord();
System.out.println(key);
Defination defns = new Defination(wmap.get(key).getDef()); //null pointer exception here
line = key + "=" + defns.getDef();

if (line != null) {
pstrim.println(line);
}
}
stream.close();
} catch (IOException IO) {
}

}

为什么会出现 NullPointerException 以及如何修复它?

最佳答案

显然,您的映射包含一个映射到 null 的键。 Map 接口(interface)的某些实现允许 null 键和/或 null 值。

来自 javadoc

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

关于java - 将 linkedhashmap 中的信息写入文件时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20950182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com