Java中int類型和Integer類型的區別:
1.int是Java的一種基本數據類型,Integer是int的包裝類(引用類型)。
2.int變量不需要實例化即可使用,而Integer變量必須要實例化后才能使用。(Integer實際上是引用類型,因此必須實例化才能使用,比如說使用關鍵字new。會看到有Integer num = 300的寫法實際上也是實例化,因為Java提供了自動裝箱拆箱的機制。)
3.int是直接存儲數據值,而Integer實際上是對象的引用,存儲的是指向實際值的指針。
4.int的默認值是0,Integer的默認值是null。
int變量和Integer變量的==比較
1.由於Integer變量實際上是對一個Integer對象的引用,所有兩個通過new生成的Integer變量用==比較永遠是不相等的(new生成的是兩個對象,內存地址不同,==比較的是內存地址)。
Integer num1 = new Integer(100); Integer num2 = new Integer(100); System.out.println(num1 == num2); // false,==比較的是內存地址
2.Integer變量和int變量比較時,只要兩個變量的值是相等的,則結果為true(包裝類Integer和基本數據類型int比較的時候,Java會自動拆箱為int,然后進行比較,實際上就變為兩個int變量的比較)。
Integer num1 = new Integer(100); int num2 = 100; System.out.println(num1 == num2); // true
3.非new生成的Integer變量和new Integer()生成的變量比較時,結果為false(非new生成的Integer變量指向的是Java常量池中的對象,而new Integer()生成的變量指向堆中新建的對象,兩者在內存中的地址不同)。
Integer num1 = new Integer(100); Integer num2 = 100; System.out.println(num1 == num2); // false
4.對於兩個非new生成的Integer對象,進行比較時,如果兩個變量的值在區間-128到127之間,則比較結果為true;如果兩個變量的值不在此區間,則比較結果為false。
Integer num1 = 100; Integer num2 = 100; Integer num3 = 128; Integer num4 = 128; System.out.println(num1 == num2); // true System.out.println(num3 == num4); // false
這是因為Java在編譯非new生成的Integer對象的時候,實際上是調用了Integer類的靜態方法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); }
通過查看Integer.valueOf()方法的源碼可以看出,Java對於-128到127之間的數會進行緩存(常量池),因此在這個范圍內的數值實際上是指向緩存(常量池)中的對象,當不在這個范圍的時候,才會在堆中new一個新的對象。
IntegerCache是Integer類的內部類,好好研究它的實現有助於對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) { 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() {} }
"不知道什么時候開始,聽故事的人變成了故事里的人。"