Double!= null导致NullPointerException [英] Double != null is causing a NullPointerException

查看:173
本文介绍了Double!= null导致NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码片段让我烦恼,其中currentRate和secondCurrentRate是Double对象,正确定义:

I have the following snippet of code that is causing me bother, where currentRate and secondCurrentRate are Double objects, correctly defined:

(currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;

这应该检查每个Double的null-ness并相应地赋值null。但是,如果secondCurrentRate为null,则会导致NullPointerException。
我已将代码段更改为:

This should check each each Double for null-ness and assign the value null accordingly. However, if secondCurrentRate is null, this causes a NullPointerException. I have changed the snippet to this:

(currentRate == null | secondCurrentRate == null) ? null : currentRate * secondCurrentRate;

这可以按预期工作。我的问题是为什么会发生这种情况?如果我在对象上调用一些方法,我可以理解它但我的理解是当在null对象上调用方法时抛出NullPointerExceptions。有一个null对象,但是没有方法调用。

And this works as expected. My question is why is this happening? I could understand it if I was calling some method on the objects but my understanding was that NullPointerExceptions were thrown when a method was called on a null object. There is a null object but there is no method call.

任何人都可以对此提供任何见解吗?这是在Java 5中运行。

Can anyone offer any insight into this? This is running in Java 5.

推荐答案

我认为您的问题出在其他地方。

I think your problem is elsewhere.

这有效:

    Double currentRate=null, secondCurrentRate =null;
    Double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;

但是如果你这样做了,它会导致NPE:

But if you've done this, it will cause a NPE:

    Double currentRate=null, secondCurrentRate =null;
    double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;

这篇关于Double!= null导致NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆