How to set to int value null? Java Android [duplic

2019-08-05 07:14发布

This question already has an answer here:

which is the best way to set already defined int to 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?

Thanks for any response.

4条回答
SAY GOODBYE
2楼-- · 2019-08-05 07:39

In this case, I would avoid using null all together.

Just use -1 as your null

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

Or, find a value that the x will never be, like Integer.MAX_VALUE or something.

查看更多
三岁会撩人
3楼-- · 2019-08-05 07:45

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

can i safely cast Integer to int?

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

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

Integer k = null;
int n = k; //Exception
查看更多
仙女界的扛把子
4楼-- · 2019-08-05 07:57

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

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.

查看更多
手持菜刀,她持情操
5楼-- · 2019-08-05 08:02

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

You can use null with Integer because that's a class instead of a primitive value.

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

查看更多
登录 后发表回答