目录

JAVA 包装类


Java 包装类

包装类提供了一种使用原始数据类型的方法(int,boolean等..)作为对象。

下表显示了原始类型和等效的包装类:

Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

有时您必须使用包装类,例如在使用 Collection 对象时,例如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,并使用length()的方法String输出 "string" 长度的类:

示例

public class Main {
  public static void main(String[] args) {
    Integer myInt = 100;
    String myString = myInt.toString();
    System.out.println(myString.length());
  }
}

亲自试一试 »