此代码导致空指针异常。我不知道为什么:
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。
最佳答案
空指针异常是对 inverse.get(animal)
的结果进行拆箱的结果。如果 inverse
不包含关键字 animal
,它返回 null
,“类型”Integer
。假设赋值给 int
引用,Java 将值拆箱到 int
中,导致空指针异常。
您应该检查 inverse.containsKey(animal)
或使用 Integer
作为局部变量类型以避免拆箱并采取相应行动。适当的机制取决于您的上下文。
关于Java:拆箱整数时出现空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1811706/