第七章、int和Integer的區(qū)別

1.基本類型:long,int,byte,float,double,char

2. 對象類型(類): Long,Integer,Byte,Float,Double,Char,String


int和Integer的區(qū)別

1、Integer是int的包裝類,int則是java的一種基本數(shù)據(jù)類型

2、Integer變量必須實例化后才能使用,而int變量不需要

3、Integer實際是對象的引用,當(dāng)new一個Integer時,實際上是生成一個指針指向此對象;而int則是直接存儲數(shù)據(jù)值

4、Integer的默認值是null,int的默認值是0



延伸:

關(guān)于Integer和int的比較

1、由于Integer變量實際上是對一個Integer對象的引用,所以兩個通過new生成的Integer變量永遠是不相等的(因為new生成的是兩個對象,其內(nèi)存地址不同)。

Integer i =newInteger(100);

Integer j =newInteger(100);

System.out.print(i == j); //false

2、Integer變量和int變量比較時,只要兩個變量的值是相等的,則結(jié)果為true(因為包裝類Integer和基本數(shù)據(jù)類型int比較時,java會自動拆包裝為int,然后進行比較,實際上就變?yōu)閮蓚€int變量的比較)

Integer i = newInteger(100);

int j =100;

System.out.print(i == j); //true

3、非new生成的Integer變量和new Integer()生成的變量比較時,結(jié)果為false。(因為非new生成的Integer變量指向的是java常量池中的對象,而new Integer()生成的變量指向堆中新建的對象,兩者在內(nèi)存中的地址不同)

Integer i =newInteger(100);

Integer j =100;

System.out.print(i == j); //false

4、對于兩個非new生成的Integer對象,進行比較時,如果兩個變量的值在區(qū)間-128到127之間,則比較結(jié)果為true,如果兩個變量的值不在此區(qū)間,則比較結(jié)果為false

Integer i =100;

Integer j =100;

System.out.print(i == j); //true

Integer i =128;

Integer j =128;

System.out.print(i == j); //false

對于第4條的原因:

java在編譯Integer i = 100 ;時,會翻譯成為Integer i = Integer.valueOf(100);,而java API中對Integer類型的valueOf的定義如下:

publicstaticIntegervalueOf(int i){

assert IntegerCache.high >=127;

if (i >= IntegerCache.low && i <= IntegerCache.high){

return IntegerCache.cache[i + (-IntegerCache.low)];

}

returnnew Integer(i);

}

java對于-128到127之間的數(shù),會進行緩存,Integer i = 127時,會將127進行緩存,下次再寫Integer j = 127時,就會直接從緩存中取,就不會new了



其他基本類型類似

publicclass TestHundun {

? ? publicstaticvoid main(String[] args) {

? ? ? ? /**? ? ? ? * long 是基本類型

? ? ? ? * Long是對象類型,進行比較時:若驗證相等則取地址,數(shù)值為(-128~127)則相等,

? ? ? ? * 因為這段數(shù)值取的是相同的地址,其余的則不相等,驗證相等可用longValue(),可用equals();

? ? ? ? */longa = 123456;

? ? ? ? longb = 123456;

? ? ? ? Long c = 123456L;

? ? ? ? Long d = 123456L;

? ? ? ? Long e = 123457L;


? ? ? ? System.out.println("(long)a==b:"+(a==b));

? ? ? ? System.out.println("(Long)c==d:"+(c==d));

? ? ? ? System.out.println("(Long)d

? ? ? ? System.out.println("正確驗證c==d:"+(c!=null&&c.equals(d)));

? ? ? ? System.out.println("longValue():"+(c.longValue()==d.longValue()));

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容