如何在java中检查Long是否为null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26638047/
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
How to check a Long for null in java
提问by BrownTownCoder
How do I check a Long value for null in Java?
如何在 Java 中检查 Long 值是否为 null?
Will this work?
这会起作用吗?
if ( longValue == null) { return blah; }
采纳答案by brso05
Primitive data types cannot be null
. Only Object
data types can be null
.
原始数据类型不能是null
. 只有Object
数据类型可以是null
.
int
, long
, etc... can't be null
.
int
, long
, 等等... 不能null
。
If you use Long
(wrapper class for long
) then you can check for null
's:
如果您使用Long
(wrapper class for long
) 那么您可以检查null
's:
Long longValue = null;
if(longValue == null)
回答by M Anouti
If the longValue
variable is of type Long
(the wrapper class, not the primitive long
), then yes you can check for null values.
如果longValue
变量是类型Long
(包装类,而不是原语long
),那么是的,您可以检查空值。
A primitive variable needs to be initialized to some value explicitly (e.g. to 0
) so its value will never be null.
原始变量需要显式初始化为某个值(例如 to 0
),因此它的值永远不会为空。
回答by Arif Ulusoy
You can check Long object for null value with longValue == null
,
you can use longValue == 0L
for long (primitive), because default value of long is 0L, but it's result will be true if longValue is zero too
您可以使用 来检查 Long 对象的空值longValue == null
,也可以 longValue == 0L
用于 long(原始),因为 long 的默认值为 0L,但如果 longValue 也为零,则结果将为 true
回答by Diablo
回答by Pavithra
As primitives(long) can't be null,It can be converted to wrapper class of that primitive type(ie.Long) and null check can be performed.
由于primitives(long)不能为null,所以可以转换为那个primitive type(ie.Long)的包装类,可以进行null检查。
If you want to check whether long variable is null,you can convert that into Long and check,
如果要检查 long 变量是否为空,可以将其转换为 Long 并检查,
long longValue=null;
if(Long.valueOf(longValue)==null)
回答by tammoj
As mentioned already primitives can not be set to the Object type null.
如前所述,原语不能设置为空对象类型。
What I do in such cases is just to use -1
or Long.MIN_VALUE
.
在这种情况下,我所做的只是使用-1
或Long.MIN_VALUE
。
回答by Srinath
Of course Primitive types cannot be null. But in Java 8 you can use Objects.isNull(longValue) to check. Ex. If(Objects.isNull(longValue))
当然原始类型不能为空。但是在 Java 8 中你可以使用 Objects.isNull(longValue) 来检查。前任。如果(Objects.isNull(longValue))
回答by Niraj
If it is Long you can check if it's null unless you go for long (as primitive data types cant be null while Long instance is a object)
如果它是 Long 你可以检查它是否为 null 除非你去很长时间(因为原始数据类型不能为 null 而 Long 实例是一个对象)
Long num;
if(num == null) return;
For some context, you can also prefer using Optional with it to make it somehow beautiful for some use cases. Refer @RequestParam in Spring MVC handling optional parameters
对于某些上下文,您还可以更喜欢将 Optional 与它一起使用,以使其在某些用例中以某种方式美观。在 Spring MVC 处理可选参数中参考@RequestParam