分配的int整数 [英] assigning int to Integer

查看:162
本文介绍了分配的int整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义一个类(作为替补在C宏)

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; 
    }

和另一个全局变量类

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

我分配是这样的:

I assign like this:

GlobalsVars.gi1 = Constants.i1;

虽然我没有得到任何编译器警告,并在1000个测试情况下工作,是有可能,这将导致GlobalVars.gi1在特殊情况下,成为空 - 就像上运行各种版本的Andr​​oid设备

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?

编辑:

我比较喜欢这样的:

if (GlobalVars.gi1 == Constants.i1)

和这正是NullPointerException异常错误发生

and this is where the NullPointerException error occured

推荐答案

在code应该运行在当前所有设备的罚款。

The code SHOULD run fine on all current devices.

有至少一个问题是:

使用静态全局变量,不建议在Android上。没有规范的静态类变量是如何对待。

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

这意味着它有可能在如果设备需要非常多的内存你的整个应用程序从内存中删除,如果该应用程序,然后带回前台的所有活动将从保存的实例状态被重建,但知道你的一些点不能靠你的静态变量是仍然可用。这是不是与int和整数的问题。如果你的应用程序从内存中删除,你所有的类都再一次加载应用程序被重新它与静态变量的持续性问题。

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.

这篇关于分配的int整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆