Integer 包装类和 int 基本类型
自动装箱
我们先来看一个很诡异的代码
public class Boxing {
public static void main(String[] args) {
Integer l1 = 100;
Integer l2 = 100;
System.out.println(l1 == l2); // true
Integer l3 = 300;
Integer l4 = 300;
System.out.println(l3 == l4); // false
}
}
通过这个代码的输出,我们可以发现一个很诡异的事情,那就是第一个会输出 true ,而第二个会输出 false。事实上,Java 会进行自动的装箱,就是说,通过反编译后的查看代码,会变成下面的样子。
public class Boxing {
public static void main(String[] args) {
Integer l1 = Integer.valueOf(100);
Integer l2 = Integer.valueOf(100);
System.out.println(l1 == l2);
Integer l3 = Integer.valueOf(300);
Integer l4 = Integer.valueOf(300);
System.out.println(l3 == l4);
}
}
所以我们可以重点看一下valueOf()
函数,看一下valueOf()
的内部实现是什么样子的。下面是valueOf()
的源码,我们可以得出结论,如果是在IntegerCache
范围内的直接就返回了,而不在IntegerCache
范围内则会新建一个对象。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这是我们已经有点明白了 100 是在IntegerCache
范围之内, 300 不在IntegerCache
的范围之内,那么IntegerCache
的范围究竟有多大呢,我们深入IntegerCache
的源码去查看一下。
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); // 取虚拟机设置的值和127之间的最大值
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1); // 因为缓存是通过一个Integer数组保存起来,所以不能超过Integer.MAX_VALUE - (-low) -1
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h; // 如果没有设置虚拟机参数,那么就是默认的 127
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 , 但是最大值可以通过虚拟机参数 -XX:AutoBoxCacheMax=<size>
进行修改,缓存的最大值会取我们设置的值和127之间的最大值,并且 缓存大小不能超过Integer.MAX_VALUE - (-low) -1
,为了验证是否正确,添加虚拟机参数-XX:AutoBoxCacheMax=2000
,并再次运行上面的代码
public class Boxing {
public static void main(String[] args) {
Integer l1 = 100;
Integer l2 = 100;
System.out.println(l1 == l2); // true
Integer l3 = 300;
Integer l4 = 300;
System.out.println(l3 == l4); // true
}
}
结果和我们预期是一样的,通过 debug 去看一下是否真的进行了修改
总结
-
当我们运行
Integer l1 = 100;
时,Java 会自动帮我们进行转换成Integer l1 = Integer.valueOf(100);
-
Integer.valueOf()
函数会对传入的参数进行比较,如果在IntegerCache
数组范围内的值会直接进行返回,不在IntegerCache
范围内的值会新建一个对象并返回 -
Integer.valueOf()
函数会对传入的参数进行比较,如果在IntegerCache
数组范围内的值会直接进行返回,不在IntegerCache
范围内的值会新建一个对象并返回 -
IntegerCache
的最大值可以进行通过虚拟机参数-XX:AutoBoxCacheMax=<size>
进行修改,而最小值无法进行修改。