總結Java中的Integer和int的區別詳細解析

來源:互聯網
上載者:User
上面的一篇提到過,為什麼Java泛型為什麼用對象而不是原始類型?但是對Integer和int這兩個的區別還是不怎麼懂,就繼續百度了一下,找到了一篇大佬的文章,感覺還是不錯的,就轉載分享一下。

Integer和int的區別

Integer是int提供的封裝類,而int是Java的基礎資料型別 (Elementary Data Type); Integer預設值是null,而int預設值是0; 聲明為Integer的變數需要執行個體化,而聲明為int的變數不需要執行個體化; Integer是對象,用一個引用指向這個對象,而int是基本類型,直接儲存數值。

除了知道Integer和int最基本的區別外,還需要瞭解一點其他關於Integer和int實際使用中的回遇到的問題。
否則如果面試官再問一下Integer i = 1;int ii = 1; i==ii為true還是為false?估計就有一部分人答不出來了,如果再問一下其他的,估計更多的人會頭腦一片混亂。所以我對它們進行了總結,希望對大家有協助。
代碼如下:

public class Main {     public static void main(String[] args) {         int a = 128;        Integer b = 127;        Integer c = 127;        Integer d = 128;        Integer e = 128;        Integer f = new Integer("128");        Integer g = new Integer("127");        Integer h = new Integer("127");          //方案一()        System.out.println("方案一:Integer與new Integer不同初始化方法的值的比較,Integer與new Integer不會相等");        //Integer e = 128;        //Integer f = new Integer("128");        if (e == f){            System.out.println("true");        }else{            System.out.println("false");        }        System.out.println("---------------------");         //方案二        System.out.println("方案二:建立兩個都是直接賦值的Integer");        //Integer b = 127;        //Integer c = 127;        if (b == c){            System.out.println("true");        }else{            System.out.println("false");        }        //Integer d = 128;        //Integer e = 128;        if (d == e){            System.out.println("true");        }else{            System.out.println("false");        }        System.out.println("---------------------");         //方案三        System.out.println("方案三:兩個都是new出來的Integer");        //Integer g = new Integer("127");        //Integer h = new Integer("127");        if (g == h){            System.out.println("true");        }else{            System.out.println("false");        }        System.out.println("---------------------");         //方案四        System.out.println("方案四:int與Integer比較");        //int a = 128;        //Integer f = new Integer("128");        if (a == f){            System.out.println("true");        }else{            System.out.println("false");        }     }}

運行結果如下:

方案一:Integer與new Integer不同初始化方法的值的比較,Integer與new Integer不會相等false---------------------方案二:建立兩個都是直接賦值的Integertruefalse---------------------方案三:兩個都是new出來的Integerfalse---------------------方案四:int與Integer比較true

總結如下:

方案一:
我先對e、f這兩個對象,使用Integer和new Integer這兩個不同的初始化方法,在對這兩個對象進行比較;

Integer e = 128;Integer f = new Integer("128"); if (e == f){    System.out.println("true");}else{    System.out.println("false");}

返回結果:false
得出結論:Integer與new Integer不會相等。e的引用指向堆,而f指向專門存放他的記憶體(常量池),他們的記憶體位址不一樣,所以為false

方案二:
建立兩個都是直接賦值的Integer,在對這兩個對象進行比較;

//Integer b = 127;//Integer c = 127;if (b == c){    System.out.println("true");}else{    System.out.println("false");}//Integer d = 128;//Integer e = 128;if (d == e){    System.out.println("true");}else{    System.out.println("false");}

返回結果:
true
false
得出結論:兩個都是直接賦值的Integer,如果數在-128到127之間,則是true,否則為false
原因: java在編譯Integer i2 = 128的時候,被翻譯成-> Integer i2 = Integer.valueOf(128);而valueOf()函數會對-128到127之間的數進行緩衝

看一下源碼大家都會明白,對於-128到127之間的數,會進行緩衝,Integer b = 127時,會將127進行緩衝,下次再寫Integer c = 127時,就會直接從緩衝中取,就不會new了。

/**     * Cache to support the object identity semantics of autoboxing for values between     * -128 and 127 (inclusive) as required by JLS.     *     * The cache is initialized on first usage.  The size of the cache     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.     * During VM initialization, java.lang.Integer.IntegerCache.high property     * may be set and saved in the private system properties in the     * sun.misc.VM class.     */     private static class IntegerCache {        static final int low = -128;        static final int high;        static final Integer cache[];         static {            // high value may be configured by property            int h = 127;            String integerCacheHighPropValue =                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");            if (integerCacheHighPropValue != null) {                try {                    int i = parseInt(integerCacheHighPropValue);                    i = Math.max(i, 127);                    // Maximum array size is Integer.MAX_VALUE                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);                } catch( NumberFormatException nfe) {                    // If the property cannot be parsed into an int, ignore it.                }            }            high = h;             cache = new Integer[(high - low) + 1];            int j = low;            for(int k = 0; k < cache.length; k++)                cache[k] = new Integer(j++);             // range [-128, 127] must be interned (JLS7 5.1.7)            assert IntegerCache.high >= 127;        }         private IntegerCache() {}    }

方案三:
我先對g、h這兩個對象,使用new Integer初始化方法,在對這兩個對象進行比較;

Integer g = new Integer("127");Integer h = new Integer("127");if (g == h){    System.out.println("true");}else{    System.out.println("false");}

返回結果:false
得出結論:兩個都是new出來的Integer對象,指向不同的兩個Integer對象,都為false

方案四:
我先對a、f這兩個對象,使用int和new Integer這兩個不同的初始化方法,在對這兩個對象進行比較;

int a = 128;Integer f = new Integer("128");if (a == f){    System.out.println("true");}else{    System.out.println("false");}

返回結果:true
得出結論:int和integer(無論new否)比,都為true,因為會把Integer自動拆箱為int再去比

相關文章:

Java教程—int與Integer的區別

Java中關於int和Integer的區別詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.