Java 包装类


章节


Java 包装类

基本数据类型(int、boolean等)无法创建对象,包装类提供了使用基本类型作为对象的方法。

下表显示了基本类型和等价的包装类:

基本类型 包装类
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

有时候必须使用包装类,例如,ArrayList不能存储基本类型(只能存储对象):

示例

ArrayList<int> myNumbers = new ArrayList<int>(); // 无效
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // 有效

创建包装类对象

要创建包装类对象,使用包装类,而不是基本类型:

示例

public class MyClass { 
  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 MyClass { 
  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()方法,可将包装类对象转换为字符串。

在下面的例子中,我们将整数转换为字符串,并使用String类的length()方法,输出myString的长度:

示例

public class MyClass { 
  public static void main(String[] args) { 
    Integer myInt = 100; 
    String myString = myInt.toString();
    System.out.println(myString.length());
  }
}
原文地址:https://www.cnblogs.com/jinbuqi/p/11751525.html