java - java.util.TreeMap 的子类在调用 put(key, value) 方法时给出 NullPointerException

标签 java collections nullpointerexception map

我想我可能在这里遗漏了一些明显的东西,但无论如何让我们看看代码。

public static class FreeMap extends TreeMap<String, Integer> {
    @Override
    public Integer put(String key, Integer value) {
        out.println(super.toString());
        out.println(super.getClass().getName()+" "+key+" : "+value);
        int i = super.put(key, value);//line 227
        assert this.size() == 1;
        return i;
    }

}
public static void main(String[] args) {
    FreeMap fm = new FreeMap();
    fm.put("A", 10);
}

运行后你会得到如下输出:

{}
com.xxxxxxxxxxxxxxxxxxxxxxxx.Graph$FreeMap A : 10
Exception in thread "main" java.lang.NullPointerException
at com.xxxxxxxxxxxxxxxxxxxxxxxx.Graph$FreeMap.put(Graph.java:227)
at com.xxxxxxxxxxxxxxxxxxxxxxxx.Graph.main(Graph.java:212)

我可以看到 super 指的是 FreeMap,而不是 TreeMap,如果它会抛出 StackOverflow 异常,我可以理解。为什么会出现空指针异常?

提前致谢

最佳答案

是的,因为 put返回以前的值:

Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

没有以前的值,因此它返回 null,然后您将其拆箱,从而导致异常。

鉴于您的方法已被声明为返回 Integer,修复起来很容易。改变这个:

int i = super.put(key, value);

为此:

Integer i = super.put(key, value);

或者理想情况下,为了可读性:

Integer oldValue = super.put(key, value);

请注意,在 键已经有一个值的情况下,这也会更有效 - 拆箱和重新装箱没有任何好处。

关于java - java.util.TreeMap 的子类在调用 put(key, value) 方法时给出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14295554/

相关文章:

Java:在构造函数或方法中传递参数?

java - 公开不同通用类型的不可修改的列表包装器

java - 什么时候可以捕获NullPointerException?

java - 添加到自定义链接列表的末尾会在 "newNode.data = .."上引发 NPE

java - 将日期 java.util.date 与 db 中的日期数据类型进行比较

java - 如何确保在显示来自 api 的无限数据时不会出现 NullPointerException。

java - 如何在远程 jmx URL 的 java 中获取所有垃圾收集器 MX bean?

java - 即使是单个学生或单个类(class),返回集合或集合的接口(interface)是一个好习惯吗?如果是,为什么?

c# - 在 C# 中,将接口(interface)列表转换为对象列表的推荐方法是什么?

android - 服务 onStartCommand 抛出 NullPointerException