深入理解Integer

自动装箱与拆箱

Integer自动装箱即将基本数据类型封装成包装类型,生成Integer对象。
Integer拆箱即将Integer对象拆箱成基本数据类型。

Integer i = 12; //自动装箱,调用了Integer.valueOf(12)静态方法生成Integer对象
int a = i; //自动拆箱,调用intValue()方法,返回i对象中的value属型。

为什么是这些方法呢,让我们看下字节码。

//javap -c Main
 public static void main(java.lang.String[]);
    Code:
       0: bipush        12
       2: invokestatic  #2   // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: aload_1
       7: invokevirtual #3   // Method java/lang/Integer.intValue:()I
      10: istore_2
      11: return

  由字节码可以看出,在12赋值给i时,是调用了Integer静态方法valueOf,传入12,再返回了一个Integer对象。在a=i时,则是调用了实例方法intValue,返回了i对象的value属性。
public int intValue() {
return value;
}

数据缓存

public static void main(String[] args) {
   
    // Integer 高频区缓存范围 -128~127
	Integer num1 = 127;
	Integer num2 = 127;
	// Integer 取值 127 == 结果为 true(值127 num1==num2 => true)
	System.out.println("值127 num1==num2 => " + (num1 == num2));
	Integer num3 = 128;
	Integer num4 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值