Java 拆箱与装箱

24 篇文章 0 订阅
2 篇文章 0 订阅

在Java中每个基本数据类型都有对应的一个类,

基本类型对应的类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
voidVoid
booleanBoolean
 - 这些对象包装器是不可变的,也就是说一旦生成了一个对应的对象之后里面的值就不能改变了。 并且它们还是final的,所以不能定义它们的子类。
 - 当我们在构造列表`(例如ArraList<Integer>)`的时候,`<>`之间只能传递对象,这个时候我们就可以传递它们对应的类。

一、装箱

  • 既然这些类都是箱子,那么把基本类型变成这些类的对象就是 装箱 的操作了。但是装箱的操作是由编译器自动来完成的,跟jvm无关。所以又称为自动装箱。
Integer a=10;//相当于是Integer a = Integer.valueOf(10);

二、拆箱

当我们将Integer对象赋给int时,将会自动拆箱。也就是编译器会完成以下动作:

int b=a;   =>   int b = a.intValue();

有时的计算可以自动拆箱和装箱,例如:

a++;

三、注意事项

/**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
  public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

从以上说明可以看到不是任何时候调用 valueOf(int i) 都会新实例化一个对象返回

Integer a = 90;
        Integer b = 90;
        Integer c = Integer.valueOf(90);
        Integer d = new Integer(90);
        if (a == b) {
            System.out.println("a==b");
        }
        if (c == b) {
            System.out.println("c==b");
        }
        if (c == d) {
            System.out.print("c==d");
        }else{
            out.println("c!=d");
}

----------
输出:
a==b
c==b
c!=d。

实际上,当初始化的值 在[-128,127]这个区间的时候只会返回已经缓存的对象,所以这个时候都是一样的,只有当初始的值不在这个范围的时候才会返回一个新new的对象,这个时候他们就不一样了

   Integer b = -129;
   if (a == b) {
            System.out.println("a==b");
        }else{
    System.out.println("a!=b");
}

输出:
a!=b

四、比较
当对象包装器直接比较的时候是跟上面的所说的一样,但是当对象包装器和一般的基本类型比较的时候就是先拆箱然后比较两者直接的“内容(这里就是数值)”,所以当一个对象包装器和一时候,如果两者的值一样那么它们就是一样的

Integer d = new Integer(90); 
       int e = 90;
        if (e == d) {
            out.println("e==d");
        }
输出:
("e==d");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值