1. 程式人生 > >Java中Integer型別的整數值的大小比較

Java中Integer型別的整數值的大小比較

       如果比較兩個數值相等的Integer型別的整數,我們可能會發現,用“==”比較(首先你必須明確“==”比較的是地址),有的時候返回true,而有的時候,返回false。比如:

Integer i = 128;
Integer j = 128;
System.out.println(i == j);//返回false

然而:

Integer m = 127;
Integer n = 127;
System.out.println(m == n);//返回true

為什麼會出現這種請況呢,因為Integer i = 128;這種方式賦值,會呼叫valueOf方法。我們發現這裡做了一些關於IntegerCache的操作。讓我們先看下valueOf的原始碼:

     這裡補充一下assert(斷言)的用法:(

assert格式

(1)assert [boolean 表示式]

如果[boolean表示式]為true,則程式繼續執行。

如果為false,則程式丟擲AssertionError,並終止執行。

(2)assert[boolean 表示式 : 錯誤表示式 (日誌)]

如果[boolean表示式]為true,則程式繼續執行。

如果為false,則程式丟擲java.lang.AssertionError,輸出[錯誤資訊]。


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

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;
            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;
            
            //把-128到127(可調)的整數都提前例項化了
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }
 
        private IntegerCache() {}
    }

      原來Integer把-128到127(可調)的整數都提前例項化了, 所以你不管建立多少個這個範圍內的Integer都是同一個物件

那麼,如何比較兩個Integer型別是否相等呢,你肯定會想到equals,沒錯,就是equals,看下equals原始碼:

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

value值是int型別(檢視原始碼可知):

private final int value;

 通過原始碼得知,是獲取Integer的基本型別值來用==比較了。所以,我們也可以這樣,通過Integer.intValue()獲取int值來直接比較。

其實,一個int型別和Integer直接“==”比較也是沒有問題的,下面給出演示:

Integer i = 128;
int j = 128;
System.out.println(i == j);//返回true

總結:

如果你用兩個Integer型別的整數做相等比較:

1.如果Integer型別的兩個數相等,如果範圍在-128~127(預設),那麼用“==”返回true,其餘的範會false。

2.兩個基本型別int進行相等比較,直接用==即可。

3.一個基本型別int和一個包裝型別Integer比較,用==也可,比較時候,Integer型別做了拆箱操作。

4.Integer型別比較大小,要麼呼叫Integer.intValue()轉為基本型別用“==”比較,要麼直接用equals比較。

擴充套件:

Long和Short型別也做了相同的處理,只不過最大值是不可調的。

參考Long的原始碼: 


public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }

參考Short的原始碼:


public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }

相關推薦

no