包装类比较是否相等

前段时间刚犯了一个非常低级的错误,就是Long型比较是否相等的时候用了==,明明数值是一样的,但是输出却是false。
Java有8个基本类型,但是它们不具有面向对象的特性,在实际开发中不能够直接参与面向对象的开发,非常不方便,为此Java为8个基本类型提供了对已经的包装类,目的就是为了让基本类型以对象的形式存在,能够参与到面向对象的开发中。
Integer和Long,包装类之间进行比较的时候,尽量使用equals,不然会出错的,因为-128~127之间,不用重新new,有缓存,这是个默认缓存,大家看看源码就知道了

/**
     * Returns a {@code Long} instance representing the specified
     * {@code long} value.
     * If a new {@code Long} instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Long(long)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * Note that unlike the {@linkplain Integer#valueOf(int)
     * corresponding method} in the {@code Integer} class, this method
     * is <em>not</em> required to cache values within a particular
     * range.
     *
     * @param  l a long value.
     * @return a {@code Long} instance representing {@code l}.
     * @since  1.5
     */
    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);
    }

阿里巴巴Java开发规范手册中也有明确规定:
在这里插入图片描述
如果非要用==,就用longValue()进行比较

public static void main(String[] args) {
		Long var1 = 127L;
		Long var2 = 127L;
		System.out.println(var1==var2);
		System.out.println(var1.equals(var2));
		Long num1 = 128L;
		Long num2 = 128L;
		System.out.println(num1==num2);
		System.out.println(num1.longValue()==num2.longValue());
		System.out.println(num1.equals(num2));
	}

结果

true
true
false
true
true

反正我是败在这上面了~ 大家多注意吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值