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 )
等…
- 为什么it.next()抛出java.util.ConcurrentModificationException?
- Guava可选作为可选参数的方法参数
- 点运算符`.`(在通用参数之前)是什么意思?
- 使用Commons或Guava将文本文件导入Java List
- 有一种优雅的方法来获取Java中多个方法返回的第一个非null值吗?
- 为什么Guava类提供了如此多的工厂方法而不是只提供varargs的方法?
- NoSuchMethodError:com.google.common.base.Stopwatch.createStarted()Lcom / google / common / base / Stopwatch
- 比较集合内的集合
- 您是否可以使用仿函数/函数式编程在Java 7中对列表进行分组(并计算每组的元素)?