记int自动装箱为Integer实例时出现的问题

今天遇到如下代码:


Integer a = 2;
Integer b = 2;
System.out.println(a==b); //返回 true
Integer a1 = 128;
Integer b1 = 128;
System.out.println(a1==b1); //返回 false


在上述代码中,同样是将int类型的数值自动装箱为Integer实例后,如果是两个2则相等,如果是两个128则不相等,这是为什么?

首先查看Integer类的源代码:

static final int low = -128;
static final int high;
static final Integer cache[];
static {
    // high value may be configured by property
    int h = 127;
    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;
}

可以看出系统把一个-128~127之间的整数自动装箱成Integer实例,并放入一个名为cache的数组中缓存起来。如果以后把一个-128~127之间的整数自动装箱成Integer实例时,实际上是直接指向对应的数组元素,因此-128~127之间的同一个整数自动装箱成Integer实例时,永远都是引用cache数组的同一个数组元素,所以它们全部相等;但每次把一个不在-128~127之间的整数自动装箱成Integer实例时,系统总是重新创建一个Integer实例,而在上一篇文章中解释过==的比较机制,所以上述程序中的a1==b1运行结果为false。

猜你喜欢

转载自blog.csdn.net/qq_37111953/article/details/79499721