1. 程式人生 > 其它 >Integer中的快取類IntegerCache

Integer中的快取類IntegerCache

https://www.cnblogs.com/wellmaxwang/p/4422855.html

對於 Integer var = ? 在-128 至 127 範圍內的賦值,Integer 物件是在IntegerCache.cache 產生,會複用已有物件,這個區間內的 Integer 值可以直接使用==進行判斷,但是這個區間之外的所有資料,都會在堆上產生,並不會複用已有物件,這是一個大坑,推薦使用 equals 方法進行判斷. 《阿里巴巴java開發手冊》

 1         Integer int1=Integer.valueOf("100");
 2         Integer int2=Integer.valueOf("100");
3 Integer int3=new Integer("100"); 4 Integer int4=new Integer("100"); 5 Integer int5=100; 6 System.out.println(int1==int2);//true 7 System.out.println(int3==int2);//false 8 System.out.println(int3==int4);//false 9 System.out.println(int1==int5);//true
10 Integer int6=Integer.valueOf("200"); 11 Integer int7=Integer.valueOf("200"); 12 Integer int8=200; 13 System.out.println(int6==int7);//false 14 System.out.println(int6==int8);//false 15 16 true 17 false 18 false 19 true 20 false 21
false

總結:

Integer物件如果在-128~127之間, 都在IntegerCache.cache中。超過這個範圍在堆空間,相當於new

 1 private static class IntegerCache {
 2         static final int low = -128;
 3         static final int high;
 4         static final Integer cache[];
 5 
 6         static {
 7             // high value may be configured by property
 8             int h = 127;
 9             String integerCacheHighPropValue =
10                 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
11             if (integerCacheHighPropValue != null) {
12                 try {
13                     int i = parseInt(integerCacheHighPropValue);
14                     i = Math.max(i, 127);
15                     // Maximum array size is Integer.MAX_VALUE
16                     h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
17                 } catch( NumberFormatException nfe) {
18                     // If the property cannot be parsed into an int, ignore it.
19                 }
20             }
21             high = h;
22 
23             cache = new Integer[(high - low) + 1];
24             int j = low;
25             for(int k = 0; k < cache.length; k++)
26                 cache[k] = new Integer(j++);
27 
28             // range [-128, 127] must be interned (JLS7 5.1.7)
29             assert IntegerCache.high >= 127;
30         }
31 
32         private IntegerCache() {}
33     }