English 中文(简体)
java: Weird Null PointerException in ternary营运人(?: )
原标题:java: weird NullPointerException in ternary operator (? : )

请考虑这项法典:

private static void doSomething(Double avg, Double min, Double sd) {
    final Double testMin;
    if (avg != null) {
        testMin = Math.max(min, avg - 3 * sd);
    } else {
        testMin = min;
    }
    System.out.println("testMin=" + testMin);

    final Double verwachtMin = avg != null ? Math.max(min, avg - 3 * sd) : min;
    System.out.println("verwachtMin=" + verwachtMin);
}

如我所知(以及我所了解的情况),变量如下:<条码>测试/code>和<条码>verwachtMin。 应同等对待。

如你所期望的那样,我只写了最后两条字,而不是第7条。 然而,当我通过这种方法将3个无效值时,我在计算<代码>verwachtMin变量时,就获得了国家空间局。

是否有任何人知道如何做到这一点? 即便条件不是<条码>,普通操作员还是对第二部分进行评价?

(Java版本 1.6.0_21)

最佳回答

Try:

final Double verwachtMin = avg != null ? new Double(Math.max(min, avg - 3 * sd)) : min;

final Double verwachtMin = avg != null ? Double.valueOf(Math.max(min, avg - 3 * sd)) : min;

The types of the alternate sides of the ternary operat或 were double and Double, which means that the Double gets unboxed to double, and then on assignment we have a boxing from double to Double. If the value of min is null then the unboxing NPEs.

问题回答

Does the ternary operator evaluate the 2nd part, even when the condition is not true

No - but it evaluations the 3rd part and 我想 in this case it tries to autoun Box min (headeding to the NPE),因为Math.max(是原始的double,并确定整个表述的返回类型。

自动箱/箱子是vil。

Auto-unboxing causes the problem. Similar question has been asked before .. You sould use double instead of Double to solve your problem..

Math.max(min, avg - 3 * sd) heremin,avg and sd are autoun Box from Double to Double which when one of them is un causes an NPE.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签