java基础-包装类

2024-03-08

需要的原因

使用基本数据类型在于效率,然而当要使用只针对对象设计的API或新特性时无法直接使用
使基本数据类型具有引用数据类型变量的相关特征

基本数据类型对应的包装类

byte  -》  Byte
short  -》  Short
int  -》  Integer
long  -》  Long
float  -》  Float
double  -》  Double
boolean  -》  Boolean
char  -》  Character
Byte、Short、Integer、Long、Float、Double、Boolean继承自Number

基本数据类型与包装类的转换

基本数据类型转换包装类

使用包装类的构造器
    new 包装类("基本数据类型的值")
    这种方式当前已过时
    布尔类型的包装类传值时,如果不是字符串"true"得到的值就是false,忽略大小写
包装类.valueOf("基本数据类型值")
    可能产生更好的空间和时间性能

包装类转基本数据类型

// 对于包装类来讲,不能进行+ - * /等运算的,所以需要转换
// 使用方式:包装类.基本数据类型名Value()
Integer i = new Integer(123123);
int i1 =  i.intValue();
Float f = new Float(123123.1F);
float f1 = f.floatValue()

String转基本数据类型、包装类

// 包装类.parse基本数据类型名称()
String i = "1";
// 当字符串不是对应的数据类型时会报错
Integer.parseInt(i);

基本数据类型、包装类转String

// 方式1:String.valueOf()
int i = 10;
String.valueOf(i);
// 方式2:基本数据类型的变量+ ""
int i = 10;
String iStr = i + "";

默认值

包装类默认值为null

自动装箱、自动拆箱

jdk5.0新特性
实际上原理就是在编译时在字节码中使用了包装类.valueOf("基本数据类型值")进行装箱和使用包装类.基本数据类型名Value()进行拆箱
基本数据类型转包装类是装箱
包装类转基本数据类型是拆箱
// 自动装箱
int i = 10;
Integer i1 = i;
// 自动拆箱
Integer i = 10;
int i1 = i;

基本数据类型与包装类做对比

// 包装类会自动拆箱
Integer m = 1000;
boolean n = 1000;
System.out.println(m == n); // true
Integer m = 1000;
int n = 1000;
System.out.println(m == n); // true

注意

创建Integer、Byte、Short、Long时
	-128到127从现有的数组中获取的
	原理是:在源码中创建了一个数据数组缓存池,创建时直接从缓存池中获取
创建Character时

	0到127从现有的数组中获取的
	原理是:在源码中创建了一个数据数组缓存池,创建时直接从缓存池中获取
创建Boolean时
	true和false从现有的数组中获取的
	原理是:在源码中创建了一个数据数组缓存池,创建时直接从缓存池中获取


{/if}