Java自动装箱和拆箱

自动装箱

定义:

将一个原始数据类型赋值给相应封装类的变量

在JDK1.5版本以后,经常使用的是下面的方法来定义一个Integer对象.

 Integer num1 = 127;

num1为一个Integer类型的引用,127为java中的基础数据类型,这种将一个基础数据类型传给其相应的封装类的做法,就是自动装箱.


原理:

查看Integer的底层发现,会直接调用Integer.valueOf的方法

 public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
    }
valueOf方法的代码为:

  /**
     * 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);
    }

其中low和high的值分别为:

  static final int low = -128;
  static final int high;

装箱就是jdk自己帮我们完成了调用Integer.valueOf(127)的方法.

自动拆箱

定义:

将一个封装类的变量赋值给相应原始数据变量,拆箱和装箱是两个相反的操作.

 Integer j=100;
 int int100=j;

原理:

拆箱过程的时候,会执行Integer 的intValue()方法.

/**
     * Returns the value of this {@code Integer} as an
     * {@code int}.
     */
    public int intValue() {
        return value;
    }

拆箱过程中JDK帮我们完成了对intValue()的调用.在上面调用j就是调用j的intValue的方法,将其返回值赋给了int100.


实例讲解:

package Object;

/**
 * 基本类型自动转换为对应的封装类的操作叫做自动装箱操作,反之叫自动拆箱操作
 * 自动装箱操作有一个自动装箱池(范围为-128~127).只要自动装箱的数在自动装箱池的范围内,则直接去池中找数据
 * Created by CXC on 2017/6/4.
 */
public class TestAutoPool {
        public static void main(String[] args) {
            Integer num1 = 127;
            Integer num2 = 127;
            System.out.println(num1==num2);//true
            Integer num3 = 128;
            Integer num4 = 128;
            System.out.println(num3==num4);//false

            Integer num5=-127;
            Integer num6=-127;
            System.out.println(num5==num6); //true

            Integer num7=-128;
            Integer num8=-128;
            System.out.println(num7==num8);//true

            Integer num9=-129;
            Integer num10=-129;
            System.out.println(num9==num10);//false

            // byte,short,int,long有自己的自动装箱池,其他基本类型都没有该自动装箱池
            //null不能自动解箱
            Integer num=null;//自动装箱不会出现错误
            int i=num;//自动解箱的时候会出错
            System.out.println(i);//java.lang.NullPointerException

            Integer j=100;
            int int100=j;
            System.out.println(int100);
        }
}


原文地址:https://www.cnblogs.com/chenxiaochan/p/7253396.html