兩個Integer對象比較

我們都知道java中對象之間用==進行的比較是內存地址之間的比較,也就是說==比較的話,如果兩個引用指向堆內存中同一個對象那麼就返回true,否則返回false。

Integer對象之間的比較

首先來看一下這樣一段代碼:

public static void main(String[] args) {
    // case 1
    Integer a1 = Integer.valueOf(60);  
    Integer b1 = 60;
    System.out.println("1:="+(a1 == b1));

    // case 2
    Integer a2 = 60;
    Integer b2 = 60;
    System.out.println("2:="+(a2 == b2));

    // case 3
    Integer a3 = new Integer(60);
    Integer b3 = 60;
    System.out.println("3:="+(a3 == b3));

    //  case 4
    Integer a4 = 129;
    Integer b4 = 129;
    System.out.println("4:="+(a4 == b4));
}

讀者可以仔細想一下這四種情況輸出什麼?

現在來公佈輸出結果:

1:=true
2:=true
3:=false
4:=false

是否多少有點驚訝?現在我們就對上面的四種情況一一進行分析。

case 1:

我們知道java中把基本類型賦給它的保證類型編譯器會自動幫我們裝箱(也就是創建一個包裝類型)。創建保證類型的時候會調用Integer.valueOf(i)方法,下面我們來看一下這個方法的源碼:

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

我們會驚奇的發現當基本數據類型在IntegerCache.low和IntegerCache.high會從IntegerCache.cache中取出數據。下面我們來分析一下IntegerCache這個類:

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;
        // 在配置文件中配置了high的值
        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() {}
}

看出來了吧,Integer類有一個默認在-128~127之間的常量緩存池,當我們的基本類型的數在這個之間的時候會指向緩存中的對象,也就是同一個對象,這就解釋case 1的情況爲什麼會返回true。

case 2:
原理在case 1中已經分析,不在重複

case 3:
可能有朋友對第三種情況比較的困惑,不是說在-128~127之間是在緩存池裏面取出數據嗎,那麼會什麼會返回false呢?別急我們來看一下Integer的構造函數:

public Integer(int value) {
    this.value = value;
}

我們可以看到Integer的構造函數之間創建一個對象,並沒有從常量池中取出對象,顯然兩個不同的對象,地址之間的比較自然而然也就不相等了。

case 4:

這個比較容易理解自動裝箱的值已經超過127,會創建兩個不同的Integer對象,返回false。

總結

我們在比較Integer對象的時候最好避免使用==號之間的比較,建議用equals方法進行Integer對象的比較。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章