例子:
public class Main {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
//true,3在Integer的cache范围[-128,127]内,c和d都指向cache中3的地址
System.out.println(c == d);
//false,321不在cache范围内,e和f是两个不同的实例
System.out.println(e == f);
//true,运算a+b自动将a和b拆箱,返回结果是int基本类型,
//Integer类型的c和int类型的运算结果a+b比较时自动拆箱,最终实际是两个int类型的值比较
System.out.println(c == (a + b));
//true, a+b的运算结果为int类型,自动装箱包装为Integer类型,
//然后两个Integer类型的对象做equals比较会被拆箱,最终比较值是否相等
System.out.println(c.equals(a + b));
//true,右侧运算结果为int类型,左侧g自动拆箱,然后通过隐式类型转换(int->long)比较
System.out.println(g == (a + b));
//false,右侧运算并包装为Integer类型,和g为Long类型,由于类型不一致,equals返回false
System.out.println(g.equals(a + b));
}
}
笔记:
1.Integer中的IntegerCache
/**
* IntegerCache的作用是节约内存,从而提高性能,默认使用缓存的范围为[-128,127],
* 自动装箱时会优先考虑是否命中cache
*/
private static class IntegerCache {
//缓存下界
static final int low = -128;
//缓存上界
static final int high;
//缓存内容
static final Integer cache[];
//IntegerCache类被初始化时调用,在整个jvm运行周期中仅被调用一次
static {
// 默认上限
int h = 127;
//获取虚拟机中配置的缓存上限
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
//配置的值转为int类型
int i = parseInt(integerCacheHighPropValue);
//配置的值不能小于127,否则取127
i = Math.max(i, 127);
// 配置的上限与下限的差值不能超过数组初始化的length上限,也就是Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// integerCacheHighPropValue不能被转化为int类型,则忽略这个参数的配置
}
}
high = h;
//初始化cache数组
cache = new Integer[(high - low) + 1];
int j = low;
//cache数组填充实际数据
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() {}
}
2.Integer中的自动装箱方法valueOf
/**
* 基本类型包装时调用
*/
public static Integer valueOf(int i) {
//值在cache范围内,返回cache中的实例
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
//不在就new一个
return new Integer(i);
}
3.Integer中的equals方法
public boolean equals(Object obj) {
//1.检查对象类型是否为Integer
if (obj instanceof Integer) {
//比较拆箱后的值
return value == ((Integer)obj).intValue();
}
return false;
}