java 检查双值是否为空(如果在 Bean 类中设置了双值)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16747391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check double value null or not(if double value set in Bean class)
提问by Shiju K Babu
I have created a Java bean class like this
我已经创建了一个这样的 Java bean 类
class BeanDemo
{
private double value;
//getter and setter
}
class myApp
{
BeanDemo beanDemo=new BeanDemo();
int val=7;
if(val<5)
{
beanDemo.setValue(23.456);
}
double value=beanDemo.getValue(); // Always returns 0.0 if it is not set
System.out.println(value);
}
How can I check if that value is null? I mean if it is not set I should print something else(say null)
如何检查该值是否为空?我的意思是如果它没有设置我应该打印其他东西(比如null)
I cannot check if its 0.0because may be i can set the value to 0.0 also.
我无法检查它是否为0.0,因为我也可以将值设置为 0.0。
Thanks
谢谢
回答by Jon Skeet
It sounds like you should be using Double
(the class) rather than double
(the primitive). There's no such thing as a null
value of type double
:
听起来您应该使用Double
(类)而不是double
(原始)。没有null
type 值这样的东西double
:
class BeanDemo {
private Double value;
public void setValue(Double value) {
this.value = value;
}
public Double getValue() {
return value;
}
}
class Test {
public static void main(String[] args) {
BeanDemo beanDemo = new BeanDemo();
int val=7;
if (val < 5) {
beanDemo.setValue(23.456);
}
Double value = beanDemo.getValue(); // value will be null
System.out.println(value);
}
}
Note that you could make your setter take double
instead of Double
if you wanted to prevent it from becoming null
again after being set once.
请注意,如果您想防止它在设置一次后再次出现,您可以让您的 setterdouble
取而代之。Double
null
回答by Evgeniy Dorofeev
Use Double instead of double, this will do exactly what you want
使用 Double 而不是 double,这将完全符合您的要求