关于Integer i1 = 100; Integer i2 = 100; Integer i3 = 127; Integer i4 = 127; System.out.println

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

在int的的包装类型Integer里面存在这个方法,当Integer大于默认的[-128,127]的时候就会new一个新对象,所以每次的引用地址都不同,所以才会出现不等于,至于这方法存在的原因有的说是对于这个范围内的数字一般使用的比较多,而不需要在常量池中new,直接栈向堆的引用过程。

     * 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);
    }

在long中也存在这样一个

    @HotSpotIntrinsicCandidate
    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值