自动装箱与拆箱

mac2025-06-16  6

自动装箱就是Java自动将原始类型值转换成对应的对象,比如将int的变量转换成Integer对象,这个过程叫做装箱,反之将Integer对象转换成int类型值,这个过程叫做拆箱。 因为这里的装箱和拆箱是自动进行的非人为转换,所以就称作为自动装箱和拆箱。

原始类型byte, short, char, int, long, float, double 和 boolean 对应的封装类为Byte, Short, Character, Integer, Long, Float, Double, Boolean。

先来看个自动装箱的代码:

public static void main(String[] args) { int i = 10; Integer n = i; }

反编译后代码如下:

public static void main(String args[]) { int i = 10; Integer n = Integer.valueOf(i); }

再来看个自动拆箱的代码:

public static void main(String[] args) { Integer i = 10; int n = i; }

反编译后代码如下:

public static void main(String args[]) { Integer i = Integer.valueOf(10); int n = i.intValue(); }

反编译得到内容可以看出,在装箱的时候自动调用的是Integer的valueOf(int)方法。而在拆箱的时候自动调用的是Integer的intValue方法。

所以,装箱过程是通过调用包装器的valueOf方法实现的,而拆箱过程是通过调用包装器的 xxxValue方法实现的。

最新回复(0)