Java 中 int 和 Integer 的区别

 

 

(1)Java 会对 -128 ~ 127 的整数进行缓存,所以当定义两个变量初始化值位于 -128 ~ 127 之间时,两个变量使用了同一地址:

Integer a=123;
Integer b=123;
System.out.println(a==b);        // 输出 true
System.out.println(a.equals(b));  // 输出 true
(2)当两个 Integer 变量的数值超出 -128 ~ 127 范围时, 变量使用了不同地址:

a=1230;
b=1230;
System.out.println(a==b);        // 输出 false
System.out.println(a.equals(b));  // 输出 true

 

 

注意 == 与 equals的区别
        
        1.== 它比较的是对象的地址
        
        2.equals 比较的是对象的内容

可以看到 使用Integer后  同样的内容对应地址是不同的

我们可以看到以上的变量定义时都是要么使用包装类要么使用基本类型类

 

证明结果是:

                使用包装类定义两个变量,这两个变量对应内容相同,但对应地址是不同的

                使用基本数据类定义两个变量,这两个变量对应内容相同,但对应地址是相同

 

 

我们接下来见证   使用包装类和基本数据类分别对应一个变量,内容相同,看结果如何

 

 Integer 变量(无论是否是 new 生成的)与 int 变量比较,只要两个变量的值是相等的,结果都为 true。

/**
 * 比较Integer变量与int变量
 */
public class Test {
    public static void main(String[] args) {
        Integer i1 = 200;
        Integer i2 = new Integer(200);
        int j = 200;
        System.out.println(i1 == j);//输出:true
        System.out.println(i2 == j);//输出:true
    }
}
包装类 Integer 变量在与基本数据类型 int 变量比较时,Integer 会自动拆包装为 int,然后进行比较,实际上就是两个 int 变量进行比较,值相等,所以为 true。

 

 

证明结果:

                    只要两个变量的值是相等的,结果为true,同时说明二人地址相同(是有一定数值范围的)

 

提问:有人可能好奇为什么不检验equals来比较?

 

equals是比较内容是否一致,显然是一致

只有==来比较才有意义

 

 

非 new 生成的 Integer 变量与 new Integer() 生成的变量比较,结果为 false

 非 new 生成的 Integer 变量与 new Integer() 生成的变量比较,结果为 false。

/**
 * 比较非new生成的Integer变量与new生成的Integer变量
 */
public class Test {
    public static void main(String[] args) {
        Integer i= new Integer(200);
        Integer j = 200;
        System.out.print(i == j);
        //输出:false
    }
}
因为非 new 生成的 Integer 变量指向的是 java 常量池中的对象,而 new Integer() 生成的变量指向堆中新建的对象,两者在内存中的地址不同。所以输出为 false。

 

 

 

证明结果:

因为非 new 生成的 Integer 变量指向的是 java 常量池中的对象,而 new Integer() 生成的变量指向堆中新建的对象,两者在内存中的地址不同。所以输出为 false

 

 

两个非 new 生成的 Integer 对象进行比较

 

//两个非 new 生成的 Integer 对象进行比较,如果两个变量的值在区间 [-128,127] 之间,比较结果为 true;否则,结果为 false。

/**
 * 比较两个非new生成的Integer变量
 */
public class Test {
    public static void main(String[] args) {
        Integer i1 = 127;
        Integer ji = 127;
        System.out.println(i1 == ji);//输出:true
        Integer i2 = 128;
        Integer j2 = 128;
        System.out.println(i2 == j2);//输出:false
    }
}
//java 在编译 Integer i1 = 127 时,会翻译成 Integer i1 = Integer.valueOf(127)

 

 

证明结果:

两个非 new 生成的 Integer 对象进行比较,如果两个变量的值在区间 [-128,127] 之间,比较结果为 true;否则,结果为 false

 

 

int 和 Integer 所占内存比较:

Integer 对象会占用更多的内存。Integer 是一个对象,需要存储对象的元数据。但是 int 是一个原始类型的数据,所以占用的空间更少。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值