Java:取消装箱整数时的空指针exception?

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

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 inverse = cellInfo.inverse(); int cell = inverse.get(animal); // null pointer exception here setCellColor(cell, color); } } } 

我在调试器中检查了它,并且所有局部变量都是非空的。 怎么会发生这种情况? BiMap来自Google Collections。

空指针exception是对inverse.get(animal)的结果进行拆箱的结果。 如果inverse不包含关键animal ,则返回null ,类型为“ Integer 。 鉴于赋值是int引用,Java将值解包为int ,从而导致空指针exception。

您应该检查inverse.containsKey(animal)或使用Integer作为局部变量类型以避免取消装箱并相应地采取行动。 正确的机制取决于您的背景。

检查inverse.containsKey(动物),BiMap逆可能没有动物。

你必须有一个堆栈跟踪。 它确切地说明发生了什么线。 发布它,我们可以告诉。

从所有发布的代码我可以“猜测”其中一个是潜在的NullPointerException

node可以为null并调用node.getParent

节点的父节点可以为null并调用parent.getChildren可以抛出Npe

一个兄弟姐妹可能是null并且调用sibling.equals可能会抛出Npe

cellInfo可能为null, cellInfo.inverse将抛出它。

最后,返回的“inverse”可能为null,而inverse.get()将抛出它。

呼!! …

所以,为了避免做这种疯狂的猜测,你为什么不发布你的堆栈跟踪,我们发现了?

它应该是这样的:

  java.lang.NullPointerException: null at YourClass.setSiblings( YouClass.java:22 ) at YourClass.setSiblng( YourClass.java: XX ) 

等…