Java:取消装箱整数时出现空指针异常?
此代码导致空指针异常。我不知道为什么:Java:取消装箱整数时出现空指针异常?,java,nullpointerexception,guava,Java,Nullpointerexception,Guava,此代码导致空指针异常。我不知道为什么: private void setSiblings(PhylogenyTree node, Color color) throws InvalidCellNumberException { PhylogenyTree parent = node.getParent(); for (PhylogenyTree sibling : parent.getChildren()) { if (! sibling.equals(node
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);
}
}
}
private void setSiblings(系统发育树节点,颜色)引发InvalidCellNumberException{
PhylogenyTree parent=node.getParent();
for(系统发育树同级:parent.getChildren()){
如果(!sibling.equals(node)){
Animal=sibling.getAnimal();
BiMap inverse=cellInfo.inverse();
int cell=inverse.get(animal);//此处出现空指针异常
setCellColor(单元格,颜色);
}
}
}
我在调试器中检查了它,所有的局部变量都是非空的。这怎么可能发生呢?BiMap来自Google Collections。空指针异常是取消绑定
inverse.get(animal)
结果的结果。如果inverse
不包含键animal
,则返回null
,“类型为”Integer
。假设赋值是对int
引用的,Java将值解装箱到int
中,从而导致空指针异常
您应该检查
inverse.containsKey(animal)
或使用Integer
作为局部变量类型,以避免取消装箱,并采取相应措施。正确的机制取决于您的上下文。您必须具有stacktrace。上面说的就是发生这件事的地方。把它贴出来,我们就知道了
从所有发布的代码中,我可以“猜测”其中一个是潜在的NullPointerException(NPE)
节点
可能为空,并调用节点.getParent
节点的父节点可能为null,调用父节点。getChildren
可能会抛出NPE
其中一个同级可能为null,调用同级。equals
可能抛出NPE
cellInfo可能为空,并且cellInfo.inverse
将抛出它
最后,返回的“inverse”可能为null,inverse.get()
将抛出它
呸
所以,为了避免这种疯狂的猜测,为什么你不发布你的stacktrace,让我们知道呢
应该是这样的:
java.lang.NullPointerException: null
at YourClass.setSiblings( YouClass.java:22 )
at YourClass.setSiblng( YourClass.java: XX )
等等 检查
反向。containsKey(动物),BiMap
。反面可能没有动物。好吧,他包括了抛出异常的那行。我不认为NullPointerException stacktrace在这种情况下有什么帮助,除了指向行之外,请参见。确切地说,在这里可以找到有关自动装箱/取消装箱的更多信息: