1. 程式人生 > >int 和 Integer 有什麼區別?談談 Integer快取值的範圍

int 和 Integer 有什麼區別?談談 Integer快取值的範圍

首先int是原始資料型別,在java中有8個這樣的原始資料型別,分別為:int,short,boolean,byte,char,float,double,long。java當中一切皆是物件,但基本資料型別除外。
Integer是int的包裝,它有一個int型別的欄位儲存資料,並且提供了基本操作,比如數學運算,位運算等。在java5中引入了自動裝箱,自動拆箱的功能,極大簡化了相關程式設計。
Integer快取值,這個問題,在廣實踐中,大量的資料操作中,都是集中在有限,較小的資料範圍內,在java5中新增了靜態工廠方法valueOf(),在呼叫它的時候,會運用到快取機制,帶來明顯的效能提升。按照javadoc,這個值預設

快取範圍是-128~127.

知識點擴充套件
1.自動裝箱,和自動拆箱
自動裝箱其實是一種語法糖,可以簡單理解為java平臺為我們自動進行一些轉化,保證不同寫法在執行時等價,他們發生在編譯階段,也就是生成的位元組碼是相同的。

Integer integer = 1;
int unboxing = integer ++;

反編譯輸出

1: invokestatic #2
java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
8: invokevirtual #3
java/lang/Integer.intValue:()I

這種快取機制不是隻有Integer實現了,同樣存在於其他的包裝類中。如Boolean Boolean.TRUE,Boolean.False,Short -128~127,Byte 全部快取,Character 快取範圍 ‘\u0000’ 到 ‘\u007F’。
原則上建議避免自動裝箱,拆箱行為,尤其是在效能敏感。

   public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
    }


    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }
    //以上是valueof

  public
static Integer valueOf(int i) { 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) { 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物件時,會呼叫public static Integer valueOf(int i) ,其中就會判斷該數值是否是在快取值範圍內,如果是,則返回一個已經建立好的Intger物件,也就是在IntegerCache中建立的Integer快取陣列,如果不在這個範圍內,就直接new 一個Integer。
當然,這個快取值預設是-128~127 ,但是是可以修改的,在vm中修改即可調整快取大小。