当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Java 自动装箱与自动拆箱

详解Java 自动装箱与自动拆箱

2020年09月10日  | 移动技术网IT编程  | 我要评论
包装器有些时候,我们需要把类似于int,double这样的基本数据类型转成对象,于是设计者就给每一个基本数据类型都配置了一个对应的类,这些类被称为包装器。包装器整体来说分为四大种: number,n

包装器

有些时候,我们需要把类似于int,double这样的基本数据类型转成对象,于是设计者就给每一个基本数据类型都配置了一个对应的类,这些类被称为包装器。

包装器整体来说分为四大种:

  1. number,number类派生出了integer,double,long,float,short,byte这六个小类分别代表了int,double,long,float,short,byte这六种基本数据类型。
  2. character,对应的基本数据类型是char。
  3. void,对应的是关键字void,这个类我们会经常在反射中看到,用于表示方法的返回值是void,这里不再赘述,后面反射章节详细讲解。
  4. boolean,对应的是基本数据类型boolean。

要记住下面两点包装器的特性:

包装器是不可变的,一旦构造了包装器,就不允许更改包装在其中的值。

  1. 包装器是final定义的,不允许定义它的子类。

自动装箱和自动拆箱

arraylist<integer> list = new arraylist<>();

list.add(3);

int x = list.get(0);

自动装箱

当我们添加int值 到一个集合元素全部是integer的集合中去时候,这个过程发生了什么?

list.add(3);

//实际上面的代码会被编译器给自动的变成下面的这个代码
list.add(integer.valueof(3))

编译器在其中所作的这个事情就叫做自动装箱。

自动拆箱

当我们取出一个集合中的元素并将这个元素赋给一个int类型的值的时候,这其中又发生了什么呢?

int x = list.get(0);

//实际上面的代码会被编译器给自动的变成下面的这个代码
int x = list.get(0).intvalue();

编译器这其中所作的这个事情就叫做自动拆箱

自动装箱和自动拆箱中的坑

integer i1 = 100;
integer i2 = 100;
integer i3 = 300;
integer i4 = 300;

system.out.println(i1 == i2);
system.out.println(i3 == i4);

这是一道经典的面试题,打印出来的结果是:

true
false

为什么会发生这样的事情,我们记得自动装箱的时候会自动调用integer的valueof方法,我们现在来看一下这个方法的源码:

public static integer valueof(int i) {
    if (i >= integercache.low && i <= integercache.high)
      return integercache.cache[i + (-integercache.low)];
    return new integer(i);
}

而这个integercache是什么呢?

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;
      string integercachehighpropvalue =
        sun.misc.vm.getsavedproperty("java.lang.integer.integercache.high");
      if (integercachehighpropvalue != null) {
        try {
          int i = parseint(integercachehighpropvalue);
          i = math.max(i, 127);
          // maximum array size is integer.max_value
          h = math.min(i, integer.max_value - (-low) -1);
        } catch( numberformatexception nfe) {
          // if the property cannot be parsed into an int, ignore it.
        }
      }
      high = h;

      cache = new integer[(high - low) + 1];
      int j = low;
      for(int k = 0; k < cache.length; k++)
        cache[k] = new integer(j++);

      // range [-128, 127] must be interned (jls7 5.1.7)
      assert integercache.high >= 127;
    }

    private integercache() {}
}

从这2段代码可以看出,在通过valueof方法创建integer对象的时候,如果数值在[-128,127]之间,便返回指向integercache.cache中已经存在的对象的引用;否则创建一个新的integer对象。

上面的代码中i1和i2的数值为100,因此会直接从cache中取已经存在的对象,所以i1和i2指向的是同一个对象,而i3和i4则是分别指向不同的对象。

这样我们就不难理解为什么一个是false,一个是true了。

其他的包装器的valueof方法也有不同的实现和不同的范围,具体的我们会在源码深度解析专栏来分析,敬请期待~

以上就是详解java 自动装箱与自动拆箱的详细内容,更多关于java 自动装箱与自动拆箱的资料请关注移动技术网其它相关文章!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网