當(dāng)前位置:首頁 > 嵌入式培訓(xùn) > 嵌入式學(xué)習(xí) > 講師博文 > integer與int的種種比較
integer與int的種種比較
時間:2018-09-21 來源:未知
近在上課過程中,發(fā)現(xiàn)之前自己一直忽略的問題,就是int與Integer的實實在在的區(qū)別。我們知道,Ingeter是int的包裝類,int的初值為0,Ingeter的初值為null,這些是眾所周知的。但是,如果”Integer i = 1;int j = 1; i==j”為true還是為false?這時就不是那么從容自若了。所以我對它們進行了總結(jié),希望對大家有幫助。
首先看代碼:
class Test
{
public static void main(String[] args)
{
Integer i = 10;
Integer j = 10;
int ii = new Integer(10);
int jj = new Integer(10);
Integer iii = new Integer(10);
Integer jjj = new Integer(10);
1. System.out.println(i==j);
2. System.out.println(ii==jj);
3. System.out.println(ii==jjj);
4. System.out.println(i==iii);
5. System.out.println(i==jj);
}
}
第一行輸出是true,兩個引用變量指向的都是常量10,這是沒有疑問的。
第二行輸出是true,兩個整型變量比較的是數(shù)值。
第三行輸出是多少這里就有些疑問了,這里要清楚,int 和 Integer比較時,會自動拆箱,所以返回true
第四行輸出是false,因為兩個引用變量指向的是兩個不同的內(nèi)存空間。
第五行輸出是true,這和第三行一樣的。
總結(jié)如下:
① 論如何,Integer與new Integer不會相等。不會經(jīng)歷拆箱過程,ii的引用指向堆,而i指向?qū)iT存放他的內(nèi)存(常量池),他們的內(nèi)存地址不一樣,所以為false
② 兩個都是new出來的,都為false
③ int和integer(無論new否)比,都為true,因為會把Integer自動拆箱為int再去比

