Skip to content

Latest commit

 

History

History
100 lines (75 loc) · 3.1 KB

File metadata and controls

100 lines (75 loc) · 3.1 KB

第15节 Java包装类

❤️💕💕java的学习指南,从入门到大师篇章。Myblog:http://nsddd.top


[TOC]

Java 包装类

包装类提供了一种将原始数据类型(intboolean等)用作对象的方法。

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

为什么没用String:前面讲过,String本身就是包装类,我们没用发现String是大写开头🐎

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());
  }
}

可以看出来和对应的 intdouble一样

另一个有用的方法是toString()方法,它用于将包装对象转换为字符串。

在下面的示例中,我们将 an转换Integer为 a String,并使用类的length()方法String输出“字符串”的长度:

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

END 链接