Java數(shù)據(jù)類型Integer與int的區(qū)別詳細解析
Integer與int的區(qū)別
如果面試官問Integer與int的區(qū)別:估計大多數(shù)人只會說道兩點,Ingeter是int的包裝類,int的初值為0,Ingeter的初值為null。
但是如果面試官再問一下Integer i = 1;int ii = 1; i==ii為true還是為false?
估計就有一部分人答不出來了,如果再問一下其他的,估計更多的人會頭腦一片混亂。
所以我對它們進行了總結(jié),希望對大家有幫助。
package com.test; /** * * @author 劉玲 * */ public class TestInteger { /** * @param args */ public static void main(String[] args) { int i = 128; Integer i2 = 128; Integer i3 = new Integer(128); //Integer會自動拆箱為int,所以為true System.out.println(i == i2); System.out.println(i == i3); System.out.println("**************"); Integer i5 = 127;//java在編譯的時候,被翻譯成-> Integer i5 = Integer.valueOf(127); Integer i6 = 127; System.out.println(i5 == i6);//true /*Integer i5 = 128; Integer i6 = 128; System.out.println(i5 == i6);//false */ Integer ii5 = new Integer(127); System.out.println(i5 == ii5); //false Integer i7 = new Integer(128); Integer i8 = new Integer(123); System.out.println(i7 == i8); //false } }
首先,17行和18行輸出結(jié)果都為true,因為Integer和int比都會自動拆箱(jdk1.5以上)。
22行的結(jié)果為true,而25行則為false,很多人都不動為什么。
其實java在編譯Integer i5 = 127的時候,被翻譯成-> Integer i5 = Integer.valueOf(127);
所以關鍵就是看valueOf()函數(shù)了。
只要看看valueOf()函數(shù)的源碼就會明白了。JDK源碼的valueOf函數(shù)式這樣的:
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
看一下源碼大家都會明白,對于-128到127之間的數(shù),會進行緩存,Integer i5 = 127時,會將127進行緩存,下次再寫Integer i6 = 127時,就會直接從緩存中取,就不會new了。
所以22行的結(jié)果為true,而25行為false。
對于27行和30行,因為對象不一樣,所以為false。
我對于以上的情況總結(jié)如下:
①無論如何,Integer與new Integer不會相等。不會經(jīng)歷拆箱過程,i3的引用指向堆,而i4指向?qū)iT存放他的內(nèi)存(常量池),他們的內(nèi)存地址不一樣,所以為false
②兩個都是非new出來的Integer,如果數(shù)在-128到127之間,則是true,否則為false。java在編譯Integer i2 = 128的時候,被翻譯成-> Integer i2 = Integer.valueOf(128);而valueOf()函數(shù)會對-128到127之間的數(shù)進行緩存
③兩個都是new出來的,都為false
④int和integer(無論new否)比,都為true,因為會把Integer自動拆箱為int再去比。
到此這篇關于Java數(shù)據(jù)類型Integer與int的區(qū)別詳細解析的文章就介紹到這了,更多相關Integer與int的區(qū)別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring實戰(zhàn)之ResourceLoaderAware加載資源用法示例
這篇文章主要介紹了Spring實戰(zhàn)之ResourceLoaderAware加載資源用法,結(jié)合實例形式分析了spring使用ResourceLoaderAware加載資源相關配置與操作技巧,需要的朋友可以參考下2020-01-01IntelliJ IDEA 2018 最新激活碼(截止到2018年1月30日)
這篇文章主要介紹了IntelliJ IDEA 2018 最新激活碼(截止到2018年1月30日)的相關資料,需要的朋友可以參考下2018-01-01Spring Boot 自動裝配原理及 Starter 實現(xiàn)原理解析
SpringBoot通過@SpringBootApplication注解簡化了依賴引入和配置,該注解包括@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan三部分,感興趣的朋友跟隨小編一起看看吧2024-09-09