Java 如何设置为int值null?爪哇安卓

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

How to set to int value null? Java Android

javaandroidnullintegerint

提问by user2899587

which is the best way to set already defined intto null?

将已定义的int设置为null的最佳方法是什么?

private int xy(){
    int x = 5;
    x = null; //-this is ERROR
    return x;
}

so i choose this

所以我选择这个

private int xy(){
    Integer x = 5;
    x = null; //-this is OK
    return (int)x;
}

Then i need something like :

然后我需要类似的东西:

if(xy() == null){
    // do something
}

And my second question can i safely cast Integer to int?

我的第二个问题可以安全地将 Integer 转换为 int 吗?

Thanks for any response.

感谢您的任何回应。

采纳答案by mrres1

In this case, I would avoid using nullall together.

在这种情况下,我会避免null一起使用。

Just use -1as your null

只需-1用作您的null

If you need -1to be an acceptable (not null) value, then use a floatinstead. Since all your real answers are going to be integers, make your null 0.1

如果您需要-1成为可接受的(非空)值,请改用 a float。因为你所有的真实答案都是整数,所以让你的 null0.1

Or, find a value that the xwill never be, like Integer.MAX_VALUEor something.

或者,找到一个x永远不会成为的值,比如Integer.MAX_VALUE什么的。

回答by Jon Skeet

You can't. intis a primitive value type - there's no such concept as a nullvalue for int.

你不能。int是一个基本值类型-有没有这样的概念,作为一个null为值int

You can use nullwith Integerbecause that's a classinstead of a primitive value.

您可以使用nullwithInteger因为它是一个而不是原始值。

It's not really clear what your method is trying to achieve, but you simply can't represent nullas an int.

不太清楚您的方法试图实现什么,但您根本无法表示nullint.

回答by assylias

Only objects can be null. Primitives (like int) can't.

只有对象可以为空。原语(如int)不能。

can i safely cast Integer to int?

我可以安全地将 Integer 转换为 int 吗?

You don't need a cast, you can rely on auto-unboxing. However it may throw a NullPointerException:

您不需要演员表,您可以依靠自动拆箱。但是它可能会抛出 NullPointerException:

Integer i = 5;
int j = i; //ok

Integer k = null;
int n = k; //Exception

回答by Eyal Schneider

Your method compiles, but will throw NullPointerException when trying to unbox the Integer...

您的方法可以编译,但在尝试取消装箱整数时会抛出 NullPointerException...

The choice between Integer and int depends on what you are trying to achieve. Do you really need an extra state indicating "no value"? If this is a legitimate state, use Integer. Otherwise use int.

Integer 和 int 之间的选择取决于您要实现的目标。你真的需要一个额外的状态来表示“没有价值”吗?如果这是合法状态,请使用 Integer。否则使用 int。