我想我可能在这里遗漏了一些明显的东西,但无论如何让我们看看代码。
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/