用int還是用Integer?

昨天例行code review時大家有討論到int和Integer的比較和使用。 這里做個整理,發(fā)表一下個人的看法。

【int和Integer的區(qū)別】

  • int是java提供的8種原始類型之一,java為每個原始類型提供了封裝類,Integer是int的封裝類。int默認(rèn)值是0,而Integer默認(rèn)值是null;
  • int和Integer(無論是否new)比較,都為true, 因為會把Integer自動拆箱為int再去比;
  • Integer是引用類型,用==比較兩個對象,其實比較的是它們的內(nèi)存地址,所以不同的Integer對象肯定是不同的;
  • 但是對于Integer i=,java在編譯時會將其解釋成Integer i=Integer.valueOf();。但是,Integer類緩存了[-128,127]之間的整數(shù), 所以對于Integer i1=127;與Integer i2=127; 來說,i1==i2,因為這二個對象指向同一個內(nèi)存單元。 而Integer i1=128;與Integer i2=128; 來說,i1==i2為false。

【各自的應(yīng)用場景】

  • Integer默認(rèn)值是null,可以區(qū)分未賦值和值為0的情況。比如未參加考試的學(xué)生和考試成績?yōu)?的學(xué)生
  • 加減乘除和比較運算較多,用int
  • 容器里推薦用Integer。 對于PO實體類,如果db里int型字段允許null,則屬性應(yīng)定義為Integer。 當(dāng)然,如果系統(tǒng)限定db里int字段不允許null值,則也可考慮將屬性定義為int。
  • 對于應(yīng)用程序里定義的枚舉類型, 其值如果是整形,則最好定義為int,方便與相關(guān)的其他int值或Integer值的比較
  • Integer提供了一系列數(shù)據(jù)的成員和操作,如Integer.MAX_VALUE,Integer.valueOf(),Integer.compare(),compareTo(),不過一般用的比較少。建議,一般用int類型,這樣一方面省去了拆裝箱,另一方面也會規(guī)避數(shù)據(jù)比較時可能帶來的bug。

【附:Integer類的內(nèi)部類IntegerCache和valueOf方法代碼】

public final class Integer extends Number implements Comparable<Integer> {

    //。。。。。。。。。。。。

    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() {}
    }

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

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容