判断两个Integer值是否相等

代码如下:

    /**
	 * @comment:Integer 类型数值比较
	 * @author:傅里叶级数
	 * @date:2018年8月
	 * @param args
	 */
	public static void main(String[] args) {
		Integer a =127;
		Integer b = 128;
		Integer c =127;
		Integer d =128;
		Integer e=-128;
		Integer f = -128;
		Integer g = -129;
		Integer h = -129;
		//打印int类型的hash值:
		System.out.println(System.identityHashCode(a));//644117698
		System.out.println(System.identityHashCode(c));//644117698
		
		System.out.println(System.identityHashCode(h));//1872034366
		System.out.println(System.identityHashCode(g));//1581781576
		
		System.out.println(a==c);//true
		System.out.println(b==d);//false
		System.out.println(f==e);//true
		System.out.println(g==h);//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
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

综上,如果两个Integer的值在[-128,127]之间,==比较返回值为true;否则可能(may)new一个对象,hash地址不同,==返回false。

转载于:https://my.oschina.net/FourierSeriesNzh/blog/1928079

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值