Wrapper包装类
什么是包装类?
基本数据类型 | 包装类 |
---|---|
byte | Byte |
int | Integer |
long | Long |
short | Short |
double | Double |
float | Float |
boolean | Boolean |
char | Character |
为什么需要有包装类?
包装类让java中的基本数据类型拥有像类一样的属性,可以使用方法,完善Java面向对象的概念
基本数据类型 包装类 String类型 三者的相互转化
基本数据类型→包装类
1.使用包装类的构造器
//构造器中填入基本数据类型
int i = 1;
Integer in1 = new Integer(i);
//构造器中填入对应的字符串
Integer in2 = new Integer("1");
2.自动装箱 (主要使用)
Integer in3 = i;
包装类→基本数据类型
1.使用包装类的方法xxxValue()
int i1 = 1;
Integer in1 = 5;
i1 = in1.intValue();
2.自动拆箱(主要使用)
int i1 = 1;
Integer in1 = new Integer("3");
i1 = in1;
System.out.println(in1);
tips:因为有自动拆箱和自动装箱,包装类和基本数据类型的界限就大大缩小
基本数据类型,包装类→String类型
通过String的valueOf()方法(主要使用)
int i1 = 1;
Integer in1 = new Integer("3");
String str1 = new String();
str1 = String.valueOf(i1);
str1 = String.valueOf(in1);
String类型→基本数据类型,包装类
通过Xxx.parseXxx()方法(主要使用)
String str1 = new String();
str1 = "123";
Integer in2 = Integer.parseInt(str1);
int i2 = Integer.parseInt(str1);
测试:
test1
private static void test1() {
Object o1 = true ? new Integer(1) : new Double(2.0);
System.out.println(o1); // 1.0
}
为什么返回1.0呢 ? 因为使用三元运算符,需要保证三元运算符两边的数字类型相同,又因为自动类型提升,使得Integer的类型自动提升为Double 导致1→1.0
test2
private static void test2() {
Integer in1 = new Integer(1);
Integer in2 = new Integer(1);
System.out.println(in1 == in2);//false
Integer in3 = 1;
Integer in4 = 1;
System.out.println(in3 == in4);//true
Integer in5 = 128;
Integer in6 = 128;
System.out.println(in5 == in6);//false
}