问题描述
此代码导致空指针异常.我不知道为什么:
This code is causing a null pointer exception. I have no idea why:
private void setSiblings(PhylogenyTree node, Color color) throws InvalidCellNumberException {
PhylogenyTree parent = node.getParent();
for (PhylogenyTree sibling : parent.getChildren()) {
if (! sibling.equals(node)) {
Animal animal = sibling.getAnimal();
BiMap<PhylogenyTree, Integer> inverse = cellInfo.inverse();
int cell = inverse.get(animal); // null pointer exception here
setCellColor(cell, color);
}
}
}
我在调试器中检查过,所有的局部变量都是非空的.这怎么可能发生?BiMap 来自 Google Collections.
I've examined it in the debugger, and all the local variables are non-null. How else could this be happening? The BiMap is from Google Collections.
推荐答案
空指针异常是对 inverse.get(animal)
的结果拆箱的结果.如果inverse
不包含键animal
,则返回null
,类型"Integer
.鉴于赋值是对 int
引用,Java 将值拆箱为 int
,导致空指针异常.
The null pointer exception is a result of unboxing the result of inverse.get(animal)
. If inverse
doesn't contain the key animal
, it returns null
, "of type" Integer
. Given that the assignment is to an int
reference, Java unboxes the value into an int
, resulting in a null pointer exception.
您应该检查 inverse.containsKey(animal)
或使用 Integer
作为局部变量类型以避免拆箱并采取相应措施.正确的机制取决于您的上下文.
You should either check for inverse.containsKey(animal)
or use Integer
as the local variable type to avoid unboxing and act accordingly. The proper mechanism depends on your context.
这篇关于Java:拆箱整数时出现空指针异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!