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 }
浙公网安备 33010602011771号