assigning int to Integer

2019-09-10 21:58发布

I defined a class (as a substitute to macros in c)

public class Constants {

    public static final int i1 = 1;
    public static final int i2 = 2; 
    }

And another "global variable" class

public class GlobalVars {
    public static Integer gi1;
    public static Integer gi2;
}

I assign like this:

GlobalsVars.gi1 = Constants.i1;

While I do not get any compiler warning and it works in 1000 test cases, is it possible that this causes GlobalVars.gi1 to become null in special cases - like on certain Android devices running various versions?

EDIT:

I compare like this:

if (GlobalVars.gi1 == Constants.i1)

and this is where the NullPointerException error occured

2条回答
看我几分像从前
2楼-- · 2019-09-10 22:36

This will work fine in all cases. It uses a feature of the Java language called autoboxing to do the conversion from the Integer object to an int primitive. http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

It doesn't matter which version of Android you run on.

查看更多
Fickle 薄情
3楼-- · 2019-09-10 22:45

The code SHOULD run fine on all current devices.

There is at least one problem with this:

Using static global variables is not recommended on Android. There is no specification how static class variables are treated.

That means it is possible that at some point if the device needs very much memory your whole app is removed from memory if the app is then brought back to the foreground all the activities will be rebuild from a saved instance state but know you can't rely on your static variables to be still available. This is not a problem with int and Integer. It is a problem with the persistence of static variables if your App is removed from memory and all your classes are load again once the app gets recreated.

查看更多
登录 后发表回答