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

标签 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)) {
            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,“类型”Integer。假设赋值给 int 引用,Java 将值拆箱到 int 中,导致空指针异常。

您应该检查 inverse.containsKey(animal) 或使用 Integer 作为局部变量类型以避免拆箱并采取相应行动。适当的机制取决于您的上下文。

关于Java:拆箱整数时出现空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1811706/

相关文章:

java - 从 byte[] 数组播放声音

java - 为什么 tomcat 看起来 .root/keystore 让我们加密

java - 右键单击 javaFX 中的 Pane 或 ImageView 时如何显示上下文菜单

java - NullPointerException 解析 Jsoup

hadoop - 在HBASE中使用协处理器时出现NullPointerException?

java - NoSuchMethodError : com. google.common.util.concurrent.MoreExecutors.directExecutor

java - Java 中的 DOM 解析器,带有属性和标签值

android - 尝试在空对象引用上调用虚拟方法 'void android.os.Bundle.putString(java.lang.String, java.lang.String)'

java - Guava 缓存获取和放置行为

java - 函数访问外部变量