Java:拆箱Integer时出现空指针异常?

此代码导致空指针异常。我不知道为什么:

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“ of

type” Integer。假设分配是给int引用的,Java将值拆箱到中int,导致空指针异常。

您应该检查inverse.containsKey(animal)Integer用作局部变量类型,以免取消装箱并采取相应措施。适当的机制取决于您的上下文。

以上是 Java:拆箱Integer时出现空指针异常? 的全部内容, 来源链接: utcz.com/qa/433208.html

回到顶部