-
什么是 Java 中的自动装箱和拆箱?
在Java中,自动装箱(Autoboxing)和拆箱(Unboxing)是Java 5引入的特性,它们允许基本数据类型(如 int、double 等)和它们对应的包装类(如 Integer、Double 等)之间进行自动转换。
自动装箱是指将基本数据类型的值自动转换为对应的包装类对象的过程。例如,将
int类型的值转换为Integer对象。
int num = 10;
Integer integerObject = num; // 自动装箱:int 转换为 Integer
自动拆箱是指将包装类对象自动转换为对应的基本数据类型的值的过程。例如,将
Integer对象转换为int类型的值。
Integer integerObject = Integer.valueOf(20);
int num = integerObject; // 自动拆箱:Integer 转换为 int
下面是一个完整的示例,演示了自动装箱和拆箱的使用:
public class AutoboxingUnboxingExample {public static void main(String[] args) {// 自动装箱int num1 = 10;Integer integerObject1 = num1; // int 转换为 Integer// 自动拆箱Integer integerObject2 = Integer.valueOf(20);int