【问题标题】:Java: null pointer exception when unboxing Integer?Java:拆箱整数时出现空指针异常?
【发布时间】:2009-11-28 05:42:16
【问题描述】:

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

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。

【问题讨论】:

标签: java nullpointerexception guava


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

检查inverse.containsKey(animal), BiMap&lt;PhylogenyTree, Integer&gt;。逆可能没有动物。

【讨论】:

    【解决方案3】:

    您必须有一个堆栈跟踪。它准确地说明了发生这种情况的路线。发布它,我们可以知道。

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

    node 可能为 null 并调用 node.getParent

    节点的父节点可能为 null,调用 parent.getChildren 可能会抛出 NPE。

    其中一个兄弟可能为 null,调用 sibling.equals 可能会引发 NPE。

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

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

    呼!!...

    所以,为了避免这种疯狂的猜测,你为什么不发布你的堆栈跟踪,让我们找出答案?

    应该是这样的:

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

    等等..

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 2015-04-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 2013-10-29
      • 1970-01-01
      相关资源
      最近更新 更多