一道腾讯笔试题--Integer的比较


如程序所示,打印的结果会是什么。

public class test{
	public static void main(String args[]){
		Integer i = 127;
		Integer j = 127;
		System.out.println(i==j);
		System.out.println(i.equals(j));
		
		Integer k = 127;
		Integer h = new Integer(127);
		System.out.println(k==h);
		System.out.println(k.equals(h));
		
		Integer m = 128;
		Integer n = 128;
		System.out.println(m==n);
		System.out.println(m.equals(n));
		
		Integer w = 128;
		Integer y = Integer.valueOf(128);
		System.out.println(w==y);
		System.out.println(w.equals(y));
		
		Integer x = 128;
		int z = 128;
		System.out.println(x==z);
		System.out.println(x.equals(z));
	}
}


对于-128~127之间的数,Integer不将其分配在堆区,所以地址是相同的打印2个true

但如果new的话,有一个Integer对象肯定分配在堆区,地址不同打印一个false一个true

对于超过+127的数,对象分配在堆区,地址不同,打印一个false一个true

由Integer.valueOf方法返回的Integer对象和w地址也不同,所以会打印一个false

由于包装类在与基本类型比较时会自动拆箱,最后两个会打印true

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值