首先我们如何理解包装类呢?
在Java中数据类型分为基本数据类型(int、double、char等)和引用数据类型(类、数组、接口)
定义一个字符串常量的方法为: String str=“hello word”;
在这里String是引用数据类型中的类,str是它的对象,因此它可以作为对象使用类的方法进行相关操作
那么基本数据类型能否创建自己的对象呢?
由此,我们引出包装类的概念:将基本数据类型封装到类中。
包装类的作用就是将基本数据类型包装成一个类,然后使用Object类进行接收
基本类型 | 包装类 |
byte | Byte |
int | Integer |
short | Short |
long | Long |
double | Double |
float | Float |
boolean | Boolean |
char | Character |
包装类分为两种类型:
对象型(Object的直接子类):Boolean、Character(char);
数值型(Number的直接子类): Byte、Double、Short、Long、Integer(int)、Float;
例子:自己定义一个包装类
class IntDemo {
private int num ;
public IntDemo(int num) {
this.num = num ;
}
public int intValue() {
return this.num ;
}
}
public static void main(String[] args) {
// 子类对象向上转型
Object obj = new IntDemo(55) ;
IntDemo temp = (IntDemo) obj ; // 向下转型
System.out.println(temp.intValue()); // 取出里面的基本数据类型操作
}
基本数据类型与包装类的相互转换
以上自己定义包装类过程复杂,出现代码复用的情况,由此,提出了装箱与拆箱的概念
装箱:将基本数据类型变为包装类对象,利用每一个包装类提供的构造方法实现装箱处理
拆箱:将包装类中包装的基本数据类型取出。利用Number类中提供的六种方法
手工装箱与拆箱
Integer num = new Integer(55) ; // 手工装箱
int data = num.intValue() ; // 手工拆箱
System.out.println(data);
自动装箱与拆箱
Integer x = 55 ;// 自动装箱
int d=x; //自动拆箱
System.out.println(++x * 5 );// 可以直接利用包装类对象操作
之前作为基本数据类型“==”比较的是数值的大小,对于对象,“==”比较的是地址
而equals()方法比较的是对象的内容是否相等
我们把基本数据类型转换为包装类后,又会出现“==”和equals的相关问题
说明:对于 Integer var = ? 在-128 至 127 范围内的赋值,Integer 对象是在IntegerCache.cache 产生,会复用
已有对象,这个区间内的 Integer 值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产
生,并不会复用已有对象
public class Test{
public static void main(String[] args) {
Integer a = 55; //自动装箱
Integer b = 55;
System.out.println(a==b);//True 在-128~127范围中,自动入池,地址相等
System.out.println(a==new Integer(55)); //False new Integer(55)装箱,基本数据类型变为包装类对象
//"=="此时比较的是地址
System.out.println(a.equals(new Integer(55))); //True equals方法比较的是两个对象的内容
Integer c = 129;
Integer d = 129; //False 超出-128~127范围,不会入池,地址不相等
System.out.println(c==d);
}
}
字符串与基本数据类型相互转换
字符串转换为基本数据类型
1. String变为int 类型(Integer类):public static int parseInt(String s) throwsNumberFormatException
2. String变为double类型(Double类):public static double parseDouble(String s) throwsNumberFormatException
3. String变为Boolean类型(Boolean类):public static boolean parseBoolean(String
基本数据类型转换为字符串
1. 任何数据类型使用了"+"连接空白字符串就变为了字符串类型。
2. 使用String类中提供的valueOf()方法,此方法不产生垃圾。
String str = String.valueOf(100) ;
System.out.println(str);