Java 中的包装器类用于将原始类型(int,char,float等)转换为相应的对象。
8 个基本类型中的每一个都有对应的包装器类。
| 原始类型 | 包装类 |
|---|---|
byte |
Byte |
boolean |
Boolean |
char |
Character |
double |
Double |
float |
Float |
int |
Integer |
long |
Long |
short |
Short |
我们还可以使用valueOf()方法将原始类型转换为相应的对象。
class Main {
public static void main(String[] args) {
// create primitive types
int a = 5;
double b = 5.65;
//converts into wrapper objects
Integer aObj = Integer.valueOf(a);
Double bObj = Double.valueOf(b);
if(aObj instanceof Integer) {
System.out.println("An object of Integer is created.");
}
if(bObj instanceof Double) {
System.out.println("An object of Double is created.");
}
}
} 输出
An object of Integer is created.
An object of Double is created. 在上面的示例中,我们使用valueOf()方法将原始类型转换为对象。
在这里,我们使用instanceof运算符检查生成的对象是Integer还是Double类型。
但是,Java 编译器可以将原始类型直接转换为相应的对象。 例如,
int a = 5;
// converts into object
Integer aObj = a;
double b = 5.6;
// converts into object
Double bObj = b; 此过程称为自动装箱。 要了解更多信息,请访问 Java 自动装箱和拆箱。
注意:我们也可以使用Wrapper类构造器将原始类型转换为包装对象。 但是在 Java 9 之后,不再使用构造器。
要将对象转换为基本类型,我们可以使用每个包装器类中存在的对应值方法(intValue(),doubleValue()等)。
class Main {
public static void main(String[] args) {
// creates objects of wrapper class
Integer aObj = Integer.valueOf(23);
Double bObj = Double.valueOf(5.55);
// converts into primitive types
int a = aObj.intValue();
double b = bObj.doubleValue();
System.out.println("The value of a: " + a);
System.out.println("The value of b: " + b);
}
} 输出:
The value of a: 23
The value of b: 5.55 在上面的示例中,我们使用intValue()和doubleValue()方法将Integer和Double对象转换为相应的原始类型。
但是,Java 编译器可以自动将对象转换为相应的原始类型。 例如,
Integer aObj = Integer.valueOf(2);
// converts into int type
int a = aObj;
Double bObj = Double.valueOf(5.55);
// converts into double type
double b = bObj; 此过程称为拆箱。 要了解更多信息,请访问 Java 自动装箱和拆箱。
-
在 Java 中,有时我们可能需要使用对象而不是原始数据类型。 例如,在使用集合时。
// error ArrayList<int> list = new ArrayList<>(); // runs perfectly ArrayList<Integer> list = new ArrayList<>();
在这种情况下,包装器类可帮助我们将原始数据类型用作对象。
-
我们可以将空值存储在包装对象中。 例如
// generates an error int a = null; // runs perfectly Integer a = null;
注意:原始类型比相应的对象更有效。 因此,当需要效率时,始终建议使用原始类型。