当前位置: 移动技术网 > IT编程>开发语言>Java > Java自动拆装箱简单介绍

Java自动拆装箱简单介绍

2019年07月19日  | 移动技术网IT编程  | 我要评论

在面试过程中,常常会有面试官问到基础的问题的时候都会问到java的拆装箱,关于这个问题其实不是很难,但是如果平时进行自学的时候不是注意,就可能一脸懵逼,所以笔者就这个问题进行一些总结,共同促进!

一、拆装箱概念

所谓的拆装箱,就是自从jdk1.5之后,java的基本类型和引用类型之间的相互转换。

1.1拆箱

拆箱就是把long,integer,double,float 等将基本数据类型的首字母大写的相应的引用类型转化为基本数据类型的动作就叫拆箱。

1.2装箱

装箱就是把byte ,int ,short, long ,double,float,boolean,char 这些java的基本数据类型在定义数据类型时不声明为相对应的引用类型,在编译器的处理下自动转化为引用类型的动作就叫做装箱。

二、拆装箱的相关应用

在jdk1.5后,当我们进行基本类型和引用类型的转换的时候就会方便:

package com.hzp.czx;
/**
 * 测试拆装箱
 * @author 夜孤寒
 * @version 1.1.1
 */
public class testdemo {
  /**
   * 拆装箱jdk1.5后
   */
  public static void first(){
    integer i=7;//基本类型-->引用类型
    int j=i;//引用类型-->基本类型
    system.out.println(j);
  }
  /**
   * 拆装箱jdk1.4
   */
  public static void second(){
    integer i=new integer(78);
    int j=i.intvalue();
    system.out.println(j);
  }
  /**
   * 测试方法
   * @param args
   */
  public static void main(string[] args) {
    first();
    second();
  }
}

上面介绍了关于拆装箱的一些基本点和使用方式,但是要使用拆装箱的话还有一些注意点需要注意,下面将这些注意点进行一些总结。

三、注意点

首先贴一段代码如下:

package com.ygh.czx;
/**
 * 关于java的拆装箱范围剖析
 * @author 夜孤寒
 * @version 1.1.1
 */
public class test {
  /**
   * 以integer类型为例
   */
  public static void first(){
    integer i=new integer(124);
    integer j=new integer(124);
    system.out.println(i==j);//false
    integer a1=-128;
    integer a2=-128;
    system.out.println(a1==a2);//true
    integer b1=-129;
    integer b2=-129;
    system.out.println(b1==b2);//false
    integer c1=127;
    integer c2=127;
    system.out.println(c1==c2);//true
    integer d1=128;
    integer d2=128;
    system.out.println(d1==d2);//false
  }
  public static void main(string[] args) {
    first();
    
  }
}

简单解释一下:

第一个结果为false的原因是因为创建了不同的对象,所以两者不一样;

但是第二个和第三个的结果为什么不一样?

下面贴出关于integer类的源码,从源码的角度来分析这个问题:

  /**
   * 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) {
    if (i >= integercache.low && i <= integercache.high)
      return integercache.cache[i + (-integercache.low)];
    return new integer(i);
  }

上面的代码是说,进行自动拆装箱的时候,是有一个范围的,一旦超出这个范围,那么指向的就不是同一个对象,而是返回一个新创建的对象了,这个范围在integer类中的一个内部私有类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() {}
  }

从这里我们可以看出,范围值为[-128,127]之间。

注意,integer、short、byte、character、long这几个类的valueof方法的实现是类似的。
double、float的valueof方法的实现是类似的。

总结:这些进行自动拆装箱的基本类型的范围如下:

1. boolean类型的值

2.所有的byte的值

3.在-128~127的short类型的值

4.在-128~127的int类型的值

5.在\ u0000~\ u00ff 之间的char类型的值

而其中double和float又有所不同,我们就以double为例子,贴出代码讨论:

package com.ygh.czx;

/**
 * 关于java的拆装箱范围剖析
 * 
 * @author 夜孤寒
 * @version 1.1.1
 */
public class test {
  /**
   * double
   */
  public static void first() {
    double i1 = 100.0;
    double i2 = 100.0;
    double i3 = 200.0;
    double i4 = 200.0;
    system.out.println(i1 == i2);//false
    system.out.println(i3 == i4);//false
  }
  /**
   * 测试方法
   */
  public static void main(string[] args) {
    first();
  }
}

注意为什么上面的代码的输出结果都是false呢?同样的我们依旧以double类中的valueof方法来讨论,贴出源码就一目了然了:

  /**
   * returns a {@code double} instance representing the specified
   * {@code double} value.
   * if a new {@code double} instance is not required, this method
   * should generally be used in preference to the constructor
   * {@link #double(double)}, as this method is likely to yield
   * significantly better space and time performance by caching
   * frequently requested values.
   *
   * @param d a double value.
   * @return a {@code double} instance representing {@code d}.
   * @since 1.5
   */
  public static double valueof(double d) {
    return new double(d);
  }

也就是说不管你的double是什么范围的值,他都是给你返回一个新的对象。float同double,就不过多赘述了。

以上就是笔者对于拆装箱的一些整理,如果读者有不同的看法可以在评论区提出,笔者再进行修改!

希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网