包装类的概念、包装类的类型转换、拆箱和装箱、缓冲区
11.3 包装类
11.3.1 什么是包装类
- 基本数据类型所对应的引用数据类型;
- Object可统一所有数据,包装类的默认值是null;
11.3.2 包装类对应
基本数据类型 | 包装类型 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char Character
11.3.3 类型转换与装箱、拆箱
- 8种包装类提供不同类型间的转换方法,可以让自身类型与其他包装类型、基本类型、字符串之间进行转换:
Number父类中提供的6个共性方法,将自身类型转换成其它数字类型;
parseXXX()静态方法,8种包装类型都有;
valueOf()静态方法; - 注意:在使用字符串构建包装类型对象时,需要保证类型兼容,否则抛出NumberFormateException异常;
- JDK5.0之后,自动装箱、拆箱。基本数据类型和包装类自动转换。
类型转换的代码练习:
public class TestEncapsulationClass {
public static void main(String[] args) {
byte baseByte = 10;
Byte b1 = new Byte(baseByte);//Java提供的Byte包装类,基于基本类型的byte进行构建
Byte b2 = new Byte("10");//基于字符串进行构建
System.out.println(Byte.MAX_VALUE);//byte类型的最大值
System.out.println(Byte.MIN_VALUE);//byte类型的最小值
System.out.println(Long.MAX_VALUE);
//Number父类提供的转型方法
byte b3 = b1.byteValue();
short s1 = b1.shortValue();
int i1 = b1.intValue();
long l1 = b1.longValue();
float f1 = b1.floatValue();
double d1 = b1.doubleValue();
//parseXXX静态方法(8种包装类型)
byte b4 = Byte.parseByte("123");//兼容的类型
System.out.println(b4);
//valueOf(基本类型)、valueOf(字符串类型)
Byte b5 = Byte.valueOf((byte)10);
Byte b6 = Byte.valueOf("20");
}
public static void m1(Object o) {
}
}
拆箱和装箱的代码:
public class TestAutoUpDownConver {
public static void main(String[] args) {
byte b = 10;
Byte b2 = new Byte(b);
Byte b3 = Byte.valueOf("20");
//JDK5之后,提供自动装箱、拆箱
Byte b4 = 40;//自动装箱,将基本类型直接复制给包装类型
byte b5 = b4;//自动拆箱,将包装类型的值,直接复制给基本类型
Student1 s = new Student1();
}
}
class Student1{
String name;
Integer age;
String sex;
Double score;
}
11.3.4 整数缓冲区
- Java预先创建了256个常用的整数包装类型对象;
- 在实际应用当中,对已创建的对象进行复用;
缓冲区演示代码:
public class TestCache {
public static void main(String[] args) {
//Byte、Short、Integer、Long,四种整数包装类型都提供了对应的cache缓冲区,提前创建了256个常用对象
//缓冲区(大量的重复应用下,节约内存的效果明显)
//缓冲//赋值过程(什么叫自动装箱)Debug
Short s1 = 100;//0x5555 调用valueOf(100),进行区间判断(-128~127),满足区间条件,将一个数组中的Short对象进行返回
Short s2 = 100;//0x5555,在类加载时,先创建了-128~127的Short类型对象,可以快速的使用,缓冲区。
Short s3 = 200;//0x6666
Short s4 = 200;//0x7777
System.out.println(s1==s2);
System.out.println(s3==s4);
System.out.println(s1.equals(s2));//判断内容
System.out.println(s3.equals(s4));//判断内容,覆盖了父类的Object equals(this==obj)
}
}
Short包装类 的 自动装箱代码:
public static Short valueOf(short s) {
final int offset = 128;
int sAsInt = s;
if (sAsInt >= -128 && sAsInt <= 127) { // must cache
return ShortCache.cache[sAsInt + offset];
}
return new Short(s);
}
private static class ShortCache {
private ShortCache(){}
static final Short cache[] = new Short[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Short((short)(i - 128));
}
}