Java基礎--基本類型與運算
阿新 • • 發佈:2018-04-08
ble fig red 緩存對象 lan BE 直接 config rop
八個基本類型:
- boolean/1
- byte/8 -2^7~2^7-1
- char/16 0~2^16-1
- short/16 -2^15~2^15-1
- int/32 -2^31~2^31-1
- float/32
- long/64 -2^63~2^63-1
- double/64
每個基本類型都有對應的包裝類型,基本類型與其對應的包裝類型之間的賦值使用自動裝箱與拆箱完成。
Integer x = 2; // 裝箱 int-->Integer int y = x; // 拆箱 Integer-->int
new Integer(num)與Integer.valueOf(num) 的區別在於,new Integer(num)每次都會新建一個對象,而Integer.valueOf(num)可能會使用緩存對象,導致多次使用Integer.valueOf(num)會取得同一個對象的引用。如以下代碼所示:
Integer a = new Integer(127); Integer b = new Integer(127); Integer c = 127; Integer d = 127; Integer e = 128; Integer g = 128; System.out.println(a == b); //false 不同對象,當然不同地址 System.out.println(a == c); //false 不同存儲地方,一個常量池,一個堆,當然不同地址 System.out.println(c == d); //true 都在常量池,且127在-128~127之間,所以引用已有的對象,無需new System.out.println(e == g); //false 128不在-128~127之間,相當於在堆中new兩個Integer對象
參照valueOf()源碼:先判斷值是否在緩存池中,如果在的話就直接使用緩存池的內容。
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i); }
Integer緩存池大小設為-128~127
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; }
因此,當num值在-127~128之間時,創建Integer對象時先查看緩存池中是否存在num值,如果沒有就在緩存池中新建,有則直接使用;若num不在-127~128之間時,valueOf使用new Integer(num)方式在堆中新建對象。
Java 還將一些其它基本類型的值放在緩沖池中,包含以下這些:
- boolean values true and false
- all byte values
- short values between -128 and 127
- int values between -128 and 127
- char in the range \u0000 to \u007F
因此在使用這些基本類型對應的包裝類型時,就可以直接使用緩沖池中的對象。
Java基礎--基本類型與運算