Interger和Int之间的一道面试题

Interger和Int之间的一道面试题

public class Test {
    public static void main(String[] args) {
        Integer i1 = 100;
        Integer i2 = 100;
        
        Integer i3 = 200;
        Integer i4=200;
        
        System.out.println(i1==i2); 
        System.out.println(i3==i4);
    }
}

上面代码中,结尾的两行输出语句分别是什么呢?

public class Test {
    public static void main(String[] args) {
        Integer i1 = 100;
        Integer i2 = 100;

        Integer i3 = 200;
        Integer i4=200;

        System.out.println(i1==i2);//true
        System.out.println(i3==i4); //false
    }
}

一些新人看到这样的答案一般会十分的疑惑,但是内部的道理却是十分的简单明了;


    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    @HotSpotIntrinsicCandidate
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

查看Integer的源码,Integer中存在着这样的一个方法–>valueOf(int i )
根据上面的注解所述,因为在[-128~+127]之间的数字使用的过于频繁和广泛,在JDK5开始,当值处于这个区间的时候,java不会再直接去频繁的new,而是去堆中调用;
而大于或小于这个区间,就会new一个新对象,每一次的地址并不相同,使用==来判断的时候,就会自然的返回了false;
(通过debug的方式,也可以看到,当整形在这个区间中的时候,(如题) i1和i2的地址是相同的,而i3,i4则不然)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值