Java中的int可以为null吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2254435/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:17:31  来源:igfitidea点击:

Can an int be null in Java?

java

提问by user220755

Can an intbe nullin Java?

可以的intnull在Java中?

For example:

例如:

int data = check(Node root);

if ( data == null ) {
 // do something
} else {
 // do something
}

My goal is to write a function which returns an int. Said intis 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.

我的目标是编写一个返回int. Saidint存储在一个节点的高度中,如果该节点不存在,它将为空,我需要检查一下。

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.

感谢您的评论,但似乎很少有人真正阅读代码下的内容,我在问我还能如何实现这个目标;很容易发现它不起作用。

采纳答案by Brian Agnew

intcan'tbe null, but Integercan. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!

int不能为空,但Integer可以。拆箱空整数时需要小心,因为这会导致很多混乱和头疼!

e.g. this:

例如这个:

int a = object.getA(); // getA returns a null Integer

will give you a NullPointerException, despite object not being null!

会给你一个NullPointerException,尽管对象不是空的!

To follow up on your question, if you want to indicate the absenceof a value, I would investigate java.util.Optional<Integer>

为了跟进你的问题,如果你想表明没有价值,我会调查java.util.Optional<Integer>

回答by Ignacio Vazquez-Abrams

No. Only object references can be null, not primitives.

不可以。只有对象引用可以为空,不能为原语。

回答by Matt Luongo

A great way to find out:

一个很好的方式来了解:

public static void main(String args[]) {
    int i = null;
}

Try to compile.

尝试编译。

回答by Jonathon Faust

In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.

在 Java 中,int 是一种原始类型,不被视为对象。只有对象可以有空值。所以你的问题的答案是否定的,它不能为空。但事情并没有那么简单,因为存在代表大多数原始类型的对象。

The class Integer represents an int value, but it can hold a null value. Depending on your checkmethod, you could be returning an int or an Integer.

Integer 类表示一个 int 值,但它可以保存一个空值。根据您的check方法,您可能会返回 int 或 Integer。

This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.

这种行为与一些更纯粹的面向对象的语言(如 Ruby)不同,在 Ruby 中,即使是像 int 这样的“原始”事物也被视为对象。

回答by BalusC

The code won't even compile. Only an fullworthy Objectcan be null, like Integer. Here's a basic example to show when you can test for null:

代码甚至不会编译。只有一个完整的Object可以null,喜欢Integer。这是一个基本示例,用于说明何时可以测试 null:

Integer data = check(Node root);

if ( data == null ) {
 // do something
} else {
 // do something
}

On the other hand, if check()is declared to return int, it can neverbe nulland the whole if-elseblock is then superfluous.

另一方面,如果check()声明为 return int,则永远不可能null,整个if-else块都是多余的。

int data = check(Node root);

// do something

Autoboxing problems doesn't apply here as well when check()is declared to return int. If it had returned Integer, then you may risk NullPointerExceptionwhen assigning it to an intinstead of Integer. Assigning it as an Integerand using the if-elseblock would then indeed have been mandatory.

check()声明为 return时,自动装箱问题也不适用于此处int。如果它已经返回Integer,那么NullPointerException在将它分配给一个intinstead of时可能会有风险Integer。将其分配为一个Integer并使用该if-else块确实是强制性的。

To learn more about autoboxing, check this Sun guide.

要了解有关自动装箱的更多信息,请查看此 Sun 指南

回答by Paul Tomblin

As @Glen mentioned in a comment, you basically have two ways around this:

正如@Glen 在评论中提到的,您基本上有两种解决方法:

  • use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
  • Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
  • 使用“越界”值。例如,如果“数据”在正常使用中永远不会是负数,则返回一个负值以表明它是无效的。
  • 使用整数。只需确保“检查”方法返回一个整数,并将其分配给一个整数而不是一个整数。因为如果在此过程中涉及到“int”,则自动装箱和拆箱可能会导致问题。

回答by Nino van Hooff

Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so

整数对象最好。如果必须使用原语,则可以使用用例中不存在的值。负身高对人来说是不存在的,所以

public int getHeight(String name){
    if(map.containsKey(name)){
        return map.get(name);
    }else{
        return -1;
    }
}

回答by Lahn

I'm no expert, but I do believe that the nullequivalent for an int is 0.

我不是专家,但我确实相信nullint的等价物是0.

For example, if you make an int[], each slot contains 0as opposed to null, unless you set it to something else.

例如,如果您创建int[],则每个插槽都包含0与 相对的null,除非您将其设置为其他内容。

In some situations, this may be of use.

在某些情况下,这可能有用。

回答by Shoaib Chikate

Along with all above answer i would like to add this point too.

除了以上所有答案,我也想补充这一点。

For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.

对于原始类型,我们有固定的内存大小,即对于 int 我们有 4 个字节,对于 char 我们有 2 个字节。null 仅用于对象,因为内存大小不固定。

So by default we have,

所以默认情况下,我们有,

   int a=0;

and not

并不是

   int a=null;

Same with other primitive types and hence null is only used for objects and not for primitive types.

与其他原始类型相同,因此 null 仅用于对象而不用于原始类型。

回答by user3550884

Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.

在 check() 方法中检查 null 并返回无效值,例如 -1 或如果为 null 则为零。然后检查将针对该值而不是传递空值。这在旧时“C”中是很正常的事情。