Java 包装类
Java 包装类
包装类提供了一种将原始数据类型(int
、boolean
等)用作对象的方式。
下表显示了原始类型和等效的包装类
原始数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | 整数 |
long | Long |
float | 浮点数 |
double | Double |
boolean | 布尔值 |
char | 字符 |
有时您必须使用包装类,例如在使用集合对象(如 ArrayList
)时,原始类型无法使用(列表只能存储对象)。
示例
ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid
创建包装对象
要创建包装对象,请使用包装类而不是原始类型。要获取值,您可以直接打印对象
示例
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
}
由于您现在正在使用对象,因此可以使用某些方法来获取有关特定对象的信息。
例如,以下方法用于获取与相应包装对象关联的值:intValue()
、byteValue()
、shortValue()
、longValue()
、floatValue()
、doubleValue()
、charValue()
、 booleanValue()
。
此示例将输出与上面示例相同的结果
示例
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}
另一个有用的方法是 toString()
方法,用于将包装对象转换为字符串。
在以下示例中,我们将一个 Integer
转换为 String
,并使用 String
类的 length()
方法输出“字符串”的长度
示例
public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
}
}