8、包装类
大约 2 分钟
包装类(Wrapper)的使用
1、包装类的使用
Java 提供了 8 种基本数据类型对应的包装类,使得基本数据类型具有类的特征
- 包装类对象调用对应的
xxxValue()
返回该对象含有的基本数据类型
2、基本数据类型、包装类、String 三者之间的转换
基本数据类型和包装类的转换
public class WrapperTest{
@Test
//基本数据类型到包装类
public void test1(){
int num1 = 10;
Integer in1 = new Integer(num1);
System.out.println(in1.toString);
Integer in2 = new Integer("123");
System.out.println(in2.toString);
Float f1 = new Float(12.3f);
Float f2 = new Float("12.3");
System.out.println(f1);
System.out.println(f2);
Boolean b1 = new Boolean(true);
Boolean b1 = new Boolean("true");
Boolean b3 = new Boolean("true123");
System.out.println(b3)//false
}
public void test2(){
@Test
//包装类到基本数据类型
//调用包装类Xxx的xxxValue()
Integer in1 = new Integer(12);
int i1 = in1.intValue();
System.out.println(i1+1);
}
}
3、自动装箱与自动拆箱
JDK5.0新特性:自动装箱与自动拆箱
- 自动装箱:允许把一个基本数据类型的值赋给包装类
- 自动拆箱:允许把包装类当做相应的基本数据类型使用
//自动装箱:
int num = 10;
Integer in1 = num;
boolean b1 = true;
Boolean b2 = b1;
//自动拆箱
int num2 = in1;
// Float c = 12; // 错误,必须保证类型一致
Float c = 12.0f;
基本数据类型,包装类和String类型的转换
- 基本数据类型,包装类到 String 类型的转换
public void test4(){
int num = 10;
//方式一:
String str = num + "";
//方式二
//调用String重载的valueOf(Xxx xxx)
float f1 = 12.3f;
String str2 = String.valueof(f1);
}
- String类型到基本数据类型、包装类
//调用包装类的parseXxx(String s)
public void test5(){
String str = "123";
//错误情况:
//int num = (int)str1;
//Integer in1 = (Integer)str1;
int num = Integer.parseInt(str1);
System.out.println(num+1);
String str1 = "true1";
boolean b1 = Boolean.parseBoolean(str1);
System.out.println(b1);//false
}
public void test3(){
int num = 10;
method(num);
}
public void method(Object obj){
System.out.println(obj);//10
}
4、包装类的题
Object o1 = true ? new Integer(1) : new Double(2.0);
System.out.println(o1);//1.0 (对于三元运算符,:两边数据类型要相同,导致数据类型提升,即为1.0)
Object o2;
if (true)
o2 = new Integer(1);
else
o2 = new Double(2.0);
System.out.println(o2);//1
public void method1() {
Integer i = new Integer(1);
Integer j = new Integer(1);
System.out.println(i == j);//false 对比的是地址值
/*Integer内部定义了IntegerCache结构,IntegerCache中定义了Integer[],保存了从-128到127范围的整数。如果我们用自动装箱的方式,给Integer赋值范围//在-128到127范围内时,可以直接使用数组中元素,就不用再去new了。目的:提高效率*/
Integer m = 1;
Integer n = 1;
System.out.println(m == n);//true
Integer x = 128;//相当于new了一个对象
Integer y = 128;//相当于new了一个对象
System.out.println(x == y);//false
}
Powered by Waline v2.15.5