privatestaticclassIntegerCache{staticfinalint low =-128;staticfinalint high;staticfinalInteger cache[];static{// high value may be configured by propertyint 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 =newInteger[(high - low)+1];int j = low;for(int k =0; k < cache.length; k++)
cache[k]=newInteger(j++);// range [-128, 127] must be interned (JLS7 5.1.7)assertIntegerCache.high >=127;}privateIntegerCache(){}}publicstaticIntegervalueOf(int i){if(i >=IntegerCache.low && i <=IntegerCache.high)returnIntegerCache.cache[i +(-IntegerCache.low)];returnnewInteger(i);}
当我们使用包装类型进行比较的时候,最好使用intValue()方法;
@Testpublicvoidtest3(){Integer i =newInteger(1);Integer j =newInteger(1);System.out.println(i == j);//false 引用地址不相等Integer m =1;Integer n =1;System.out.println(m == n);//true 读取缓存Integer x =128;//相当于new了一个Integer对象Integer y =128;//相当于new了一个Integer对象System.out.println(x == y);//false}