java中int和integer比较,integer和integer比较

先看一代代码:

	public static void main(String[] args) {
		long test = 012;
		float f = -412;
		double d = 0x12345678;
	
		Integer io1 = 59;
		int io2 = 59;
		Integer io3 = Integer.valueOf(59);
		Integer io4 = new Integer(59);
		Integer io5 = new Integer(59);

		System.out.println(io1 == io2);
		System.out.println(io1 == io3);
		System.out.println(io1 == io4);
		System.out.println(io1 == io5);
		
		System.out.println(io2 == io3);
		System.out.println(io2 == io4);
		System.out.println(io2 == io5);
		
		System.out.println(io3 == io4);
		System.out.println(io3 == io5);
		
		System.out.println(io4 == io5);
	}



输出结果为:

true
true
false
false


true
true
true


false
false


false

先给出valueof的代码:

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

如上图代码,如面中,默认如果不new的话,会维持一个integer池,范围是-128~127

前4个,

所以io1是在integer池里面的,而valueof弄出的59,也是在同一个池子里面,所以io1和io3为true。

而io2与任何的比,都是讲integer转为int,所以只要数值相同,就相等。

io4和io5为新new出的,所以比较的是内存中地址,不相等,故io1和io4不等,io1和io5不等。

后面3个,

有分析知,io2与其他比较都相等。

后面2个,

io3在池子里面,而io4和io5都是新new出来的。

最后1个,

io4和io5是新new出来的,故不等















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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值