此代码导致空指针异常。我不明白为什么:
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);
}
}
}
我在调试器中检查了它,并且所有局部变量都是非null。这怎么可能发生? BiMap来自Google Collections。
答案 0 :(得分:45)
空指针异常是取消装箱inverse.get(animal)
结果的结果。如果inverse
不包含密钥animal
,则会返回类型为“null
的{{1}}”。鉴于赋值是Integer
引用,Java将值拆分为int
,从而导致空指针异常。
您应该检查int
或使用inverse.containsKey(animal)
作为本地变量类型,以避免取消装箱并采取相应措施。正确的机制取决于你的背景。
答案 1 :(得分:4)
检查inverse.containsKey(animal), BiMap<PhylogenyTree, Integer>
。反向可能没有动物。
答案 2 :(得分:0)
您必须拥有堆栈跟踪。它确切地说明发生了什么线。发布它,我们可以告诉。
从所有发布的代码中,我可以“猜测”其中一个是潜在的NullPointerException(NPE)。
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 )
等..