11_Int和Integer的区别(重点)

1,来,先来一道考题,你看做对了吗?

Integer i1 = new Integer(12);
Integer i2 = new Integer(12);
System.out.println(i1 == i2);

Integer i3 = 126;
Integer i4 = 126;
int i5 = 126;
System.out.println(i3 == i4);
System.out.println(i3 == i5);

Integer i6 = 128;
Integer i7 = 128;
int i8 = 128;
System.out.println(i6 == i7);
System.out.println(i6 == i8);

以上这些输出的答案是什么?true or false? why?

你可以自己先思考,再看后面的答案分析。

 

 

 

答案揭晓

分情况来比较:F T T(自动拆箱,数值) F T(自动拆箱,数值)

  • 都定义为Integer的比较:
new:一旦new,就是开辟一块新内存,结果肯定是false
不new:看范围
Integer做了缓存,-128至127,当你取值在这个范围的时候,会采用缓存的对象,所以会相等
当不在这个范围,内部创建新的对象,此时不相等
  • Integer和int的比较:
实际比较的是数值,Integer会做拆箱的动作,来跟基本数据类型做比较
此时跟是否在缓存范围内或是否new都没关系

源码分析:

当我们写Integer i = 126,实际上做了自动装箱:Integer i = Integer.valueOf(126);
分析这段源码
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
//IntegerCache是Integer的内部类
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];
    static {
        // high value may be configured by property
        int h = 127;​​

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值