Java中的int可以为null吗? [英] Can an int be null in Java?
问题描述
Java中的 int
可以 null
吗?
Can an int
be null
in Java?
例如:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
我的目标是编写一个返回 int
的函数。所说的 int
存储在一个节点的高度,如果该节点不存在,它将为null,我需要检查它。
My goal is to write a function which returns an int
. Said int
is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
我这样做是为了完成家庭作业,但这个特定的部分不是作业的一部分,它只是帮助我完成我正在做的事情。
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
感谢您的评论,但似乎很少有人真正阅读过代码下的内容,我在问我还能如何实现这一目标;很容易弄清楚它不起作用。
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
推荐答案
int
不能为空,但整数
可以。拆箱null整数时你需要小心,因为这会引起很多混乱和头疼!
int
can't be null, but Integer
can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
例如。这个:
int a = object.getA(); // getA returns a null Integer
会给你一个 NullPointerException
,尽管对象不是空的!
will give you a NullPointerException
, despite object not being null!
要跟进你的问题,如果你想指出一个值的缺席 ,我会调查 java.util.Optional< Integer>
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
这篇关于Java中的int可以为null吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!