2014-04-01 72 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。 –