int i=127;
Integer i2=127;
Integer i3=new Integer(127);
//打印hashCode
System.out.println(System.identityHashCode(i));
System.out.println(System.identityHashCode(i3));
System.out.println(i==i2);
System.out.println(i==i3);
System.out.println(i2==i3);
结果
1705736037
455659002
true
true
false
这里i==i3为true ,开始没有弄清楚,因为i3是new 出来的 讲道理的他们的地址是不同的 所有应该为false 但是后来问了老师在查询了一些资料发现,int 和 Integer进行比较时,Integer会自动拆箱调用intValue()方法返回一个int值,这个时候两个int值指向都是同一个栈中的地址,所以他们是true.
i2==i3 false是因为 Integer和Integer进行比较的时候并不会进行拆箱所以他们地址不一样为flase
大家都知道Integer是int的包装类,1.5后进行了自动装箱,和自动拆箱的操作;
Integer a = 128;
//编译后的class文件中
Integer a = Integer.valueOf(128);
//这里会调用Integer.valueOf 返回表示指定的 int值的 Integer实例。
方法源代码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high) //判断值是否在-128和127之间
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这里有一个IntegerCache是Integer 中的静态内部类,这里我贴一部分源码出来
private static class IntegerCache {
static final int low = -128;//这里可以看出最小值是-128
static final int high; //最大值在下面被赋值为127
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() {}
}
总的来说就是 创建Integer 如果你的值在-128到127之间会被缓存到IntegerCache.cache这个数组中,如果下次进行创建会直接返回调用缓存中的值,如果你的值大于127那么就会重新new Integer()。最大边界可以通过-XX:AutoBoxCacheMax进行配置,但也不会大于Integer.MAX_VALUE最大值(2^31次方,2147483648,正21亿多)。
为什么要这样做?