2014-04-01 70 views
1

虽然这已经在包括SO在内的各种论坛中详细讨论过,并且我已阅读了大部分专家的回复,但下面的问题是令人困惑的我。为什么int不能与null比较,但Integer可以与null比较

我有几个integer变量,我的要求是在执行少量语句前检查null。所以首先我宣布为int (I don't have knowledge on int and Integer)

int a,b,c; 
if(a == null) { 
    //code here 
} 

但是编译器不允许我这样声明。

在谷歌搜索后,专家建议我使用Integer,而不是int当我变了样下面的代码

Integer a,b,c; 
if(a == null) { 
    //code here 
} 

这是罚款与编译器为Integer被定义为在Java Objectint是不。

现在我的代码已经成为一些声明int和一些Integer

任何人都可以提出,如果声明Integer可以得到同样的结果int也可以更改我的所有声明到Integer

谢谢你的时间。

回答

3
int a,b,c; 
if (a == null) { 
    //code here 
} 

此代码没有意义,因为原始的int类型不能为空。即使你考虑过自动装箱,int a保证在装箱前有一定的价值。

Integer a,b,c; 
if (a == null) { 
    //code here 
} 

该代码是有道理的,因为对象Integer类型可以是空(没有值)。

就功能而言,Object vs内置类型实际上确实有点不同(由于它们的不同性质)。

Integer a,b,c; 
if (a == b) { 
    // a and b refer to the same instance. 
    // for small integers where a and b are constructed with the same values, 
    // the JVM uses a factory and this will mostly work 
    // 
    // for large integers where a and b are constructed with the same values, 
    // you could get a == b to fail 
} 

int a,b,c; 
if (a == b) { 
    // for all integers were a and b contain the same value, 
    // this will always work 
} 
+0

感谢@Edwin Buck的回复...我在与变量进行比较时没有任何问题,但是我的应用程序有一些功能迫使我与null比较......您能否使用'Integer'来指导我而不是'int'或者是否有任何问题。 – Siva

+0

处理必须采用Object的项目时,使用Integer非常重要。例如,你可以有一个ArrayList 但你不能有一个ArrayList ;因为int不能转换为Object,所以'add(T item)'方法无法实现。 (因为'int'不是'Object'的子类,而'Integer'是)。这些天自动装箱隐藏大部分这些区别,但偶尔了解差异仍然很重要。 –

+0

如果我不处理对象..我还可以采取'整数'?用于存储值并将这些值用于运算操作?感谢您的持续帮助 – Siva

3

int是原始类型,不是可以为空的值(它不能为空)。 Integer是一个类对象,如果尚未实例化,则该对象可以为null。使用Integer而不是int不会真正影响任何功能,并且如果您将“int”更改为“Integer”,则您的代码将表现相同。

+0

@RhinoFeeder ..感谢您的回复。所以我可以改变从'int'到'Integer'我所有declerations没有丢失任何功能。 – Siva

+0

正确。他们会发挥相同的功能。 –

+0

@RhinoFeeder也就是说,如果有人不会像[this](https://gist.github.com/christopherperry/7815316)那样来Integer。 –