java中的包装类提供了将原始数据类型转换为对象,以及将对象转换为原始数据类型的机制。
自J2SE 5.0以来,自动装箱和取消装箱功能将原始对象和对象自动转换为原始数据类型。将原始数据类型自动转换为对象称为自动装箱,反之亦然。
java.lang
包的八个类在java中称为包装类。八个包装类的列表如下:
基本类型 | 包装类 |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
为什么需要包装类?
将原始类型和包装类分开以保持简单是一个明智的做法。当需要一个适合像面向对象编程的类型时就需要包装类。当希望数据类型变得简单时就使用原始类型。
原始类型不能为null
,但包装类可以为null
。包装类可用于实现多态性。
下面是一个简单的程序,显示了java中包装类的不同方面应用。
import java.util.ArrayList; import java.util.List; public class WrapperClasses { private static void doSomething(Object obj){ } public static void main(String args[]){ int i = 10; char c = 'a'; // 原始数据很容易使用 int j = i+3; // 由包装类实现的多态性,不能在这里传递原始数据 doSomething(new Character(c)); List<Integer> list = new ArrayList<Integer>(); // 包装类可以在集合中使用 Integer in = new Integer(i); list.add(in); // 自动装箱负责原始到包装器类的转换 list.add(j); //包装类可以为 null in = null; } }
包装类示例:原始类型到包装类型
public class WrapperExample1 { public static void main(String args[]) { // Converting int into Integer int a = 20; Integer i = Integer.valueOf(a);// converting int into Integer Integer j = a;// autoboxing, now compiler will write Integer.valueOf(a) // internally System.out.println(a + " " + i + " " + j); } }
输出结果 -
20 20 20
包装类示例:包装类型到原始类型
public class WrapperExample2 { public static void main(String args[]) { // Converting Integer to int Integer a = new Integer(3); int i = a.intValue();// converting Integer to int int j = a;// unboxing, now compiler will write a.intValue() internally System.out.println(a + " " + i + " " + j); } }
输出结果 -
3 3 3