java的int與Integer區(qū)別

一句話:int是基本數(shù)據(jù)類型,Integer是類。

詳細(xì):

  1. 由于是對(duì)象,Integer默認(rèn)值是null,而int是0;Integer需要實(shí)例化才能使用,int可以直接使用。
  2. Integer是int的包裝類。再integer與int類型直接比較的時(shí)候系統(tǒng)會(huì)自動(dòng)做些動(dòng)作方便使用(比如自動(dòng)對(duì)Integer解析成int再比較)。

一些案例幫助理解:

Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.print(i == j); //false,引用類型比較

Integer i = new Integer(100);
int j = 100;
System.out.print(i == j); //true,Integer會(huì)自動(dòng)解析成int再比較

Integer i = new Integer(100);
Integer j = 100;
System.out.print(i == j); //false,前者指向堆內(nèi)存中的對(duì)象,后者指向java常量池中的對(duì)象

Integer i = 128; // 相當(dāng)于Integer i = Integer.valueOf(128),-128到127會(huì)被緩存,超過(guò)范圍則會(huì)new
Integer j = 128;
System.out.print(i == j); //false

Integer i = 100;
Integer j = 100;
System.out.print(i == j); //true,因?yàn)楸痪彺?,?shí)際上對(duì)應(yīng)常量池中同一個(gè)對(duì)象

參考文章:
int與Integer區(qū)別

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

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

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