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

2019-08-05 06:57发布

问题:

This question already has an answer here:

  • What is the difference between an int and an Integer in Java and C#? 26 answers

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.

回答1:

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.



回答2:

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.



回答3:

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:

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.