< font style = "color:rgb(77, 77, 77)" >< font face = """ >< font style = "font-size:16px" >/**
* 自动装拆箱
*/
public static void main(String[] args) {
Integer integer0 = 127;
Integer integer1 = 127;
System.out.println(integer0 == integer1);//等于true
Integer integer2 = 128;
Integer integer3 = 128;
System.out.println(integer2 == integer3);//等于false
/** 源码
* public static Integer valueOf(int i) {
* if (i >= Integer.IntegerCache.low && i <= Integer.IntegerCache.high)
* return Integer.IntegerCache.cache[i + (-Integer.IntegerCache.low)];
* return new Integer(i);
* }
* 通过上我们发现,如果他的int值在最高和最低之间,他直接返回cache内的数据
* 否则, new Integer(i);
* 那么最高值:?=high 127 ,最低值:?=low -128,
* 所以:在-128至127内,他们引用的是缓存内的数据,地址相同,所以为true。超过此则为false
*
* 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() {}
* }
*
*/
}</ font ></ font ></ font >
|