Java中Integer的變數比較源碼解析

來源:互聯網
上載者:User
面試例子:
public static void main(String arg[]){       Integer a=3;       Integer b=3;       System.out.println(a==b);       System.out.println(a.equals(b));       a=3333;       b=3333;       System.out.println(a==b);       System.out.println(a.equals(b));   } 

此程式列印出來的結果分別為:true,true,false,true。那麼為什麼會出現這種結果呢。 原因分析

我們要知道當給一個Integer對象賦一個int值時,Integer的valueOf方法會被調用。那麼,我們看看Integer的valueOf方法到底做了些什麼。源碼如下:

代碼一:

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);}

代碼二:

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) {            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);        }        high = h;        cache = new Integer[(high - low) + 1];        int j = low;        for(int k = 0; k < cache.length; k++)            cache[k] = new Integer(j++);    }    private IntegerCache() {}}

通過代碼一我們可以看出,當valueOf傳入的值在IntegerCache.low和IntegerCache.high之間時,Integer被賦的值將從IntegerCache.cache數組中獲得,也就是通過緩衝中獲得。

再看代碼二,IntegerCache.low為常量-128。而IntegerCache.high如果在啟動JVM時沒有指定-XX:AutoBoxCacheMax參數,預設為127。綜合兩段代碼,我們可以知道,在預設情況下,在-128到127之間的資料在賦值時會從緩衝中獲得。 結論

因此,在-128到127之間的資料多次獲得的均為同一個對象,而超出這個範圍的資料將會建立一個新的對象,只能通過equals方法比較的才是對象的值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.