Java中的自动装箱、拆箱与注解
一、自动装箱与拆箱
在Java编程中,自动装箱和拆箱是JDK 5引入的重要特性,它们极大地简化了基本数据类型和其包装类之间的转换操作。
1. 装箱与拆箱基础
在早期的Java版本中,若要将基本数据类型封装到对应的包装类对象中,需要手动创建对象。例如:
// Demonstrate a type wrapper.
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = iOb.intValue();
System.out.println(i + " " + iOb); // displays 100 100
}
}
在上述代码里, Integer iOb = new Integer(100);
这行代码把整数100封装进 Integer
对象 iOb
中,此过程被称作装箱;而 int i = iOb.intValue();
这行代码则从 Integer
对象 iOb
中提取出整数值,该过程被称为拆箱。
2. 自动装箱与拆箱
自JDK 5起,Java引入了自动装箱和自动拆箱特性。自动装箱指的是,当需要某个类型的对象时,基