Java:包装类自动装箱拆箱


JDK1.5或以上,可以支持基本类型和包装类型之间的自动装箱、自动拆箱,这简化了基本类型和包装类型之间的转换。

  • 自动装箱:基本数据类型值 自动转化为 包装类对象
  • 自动拆箱:包装类对象 自动转化为 基本数据类型值

比如


public class Test043_Integer {
    public static void main(String[] args) {
// JKD1.5 之前
// Integer o = new Integer(1);
// Integer o = Integer.valueOf(1);
// JDK1.5 之后
// 自动装箱,这里会自动把数字1包装成Integer类型的对象
        Integer o = 1;
// JKD1.5 之前
// Integer o = new Integer(1);
// int i = o.intValue();
// JDK1.5 之后
// Integer o = new Integer(1);
// 自动拆箱,这里会自动把对象o拆箱为一个int类型的数字,并把数字赋值给int类型的变量i
        int i = o;
    }

其他的基本类型和包装类型之间的转换,与此类似。

注意事项:

  1. 不同类型的基本数据类型和包装类,是不可以自动装箱拆箱的,例如int和Long;
  2. 给Byte Short Character赋值时,需要考虑 常量优化机制。

代码

public class Test {
   public void test1(int i) {
   }

   public void test2(Integer i) {
   }

   public void test3(long i) {
   }

   public void test4(Long i) {
   }

   // 不同类型的基本数据类型和包装类,不可以自动装箱拆箱
   public static void main01(String[] args) {
       Test043_Test t = new Test043_Test();
       t.test1(1);// 编译通过 int i = 1; 正常赋值
       t.test2(1);// 编译通过 Integer i = 1; 自动装箱
       t.test3(1);// 编译通过 long i = 1; 隐式类型转换
// 编译报错
// 错误的代码:Long i = 1;
// int和Long 之间没有任何关系
// t.test4(1);
       t.test4(1L);// 编译通过 Long i = 1L; 自动装箱
   }

   public static void main(String[] args) {
// 注意: 自动装箱时候 要保证类型一致
// Long l = 2; ERROR
       Long l2 = 23L;
// int t = l2; ERROR
       long t = l2;
// 给Byte Short Character赋值时,需要考虑 常量优化机制
       Byte b1 = 2;
       Byte b2 = 127;
// Byte b3 = 128; ERROR
       Character c1 = 3;
       Character c2 = '\u0989';
       Character c3 = 65535;
// Character c4 = 65536; ERROR
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值