java入门 14 03\21
包装类(Wrapper)的使用
-
包装类的使用:
1. java提供了八种基本数据类型对应的包装类,使得基本数据类型的变量具有类的特征。 2. 掌握的:基本数据类型、包装类、String三者之间的相互转换。
-
基本数据类型 —> 包装类 :调用包装类的构造器。
eg:
public void test1() { int num1 = 10; Integer in1 = new Integer(num1); System.out.println(in1.toString()); //就可以调用类的方法了,不然int类型不可直接调用,。 }
Float f1 = new Float(12.3f);
Float f2 = new Float("12.3");
//两者是相同的。 都是把f1/2赋值上12.3.
-
包装类 ----> 基本数据类型: 调用包装类的xxxValue()
eg:
public void test2() { Integer in1 = new Integer(12); int i1 = in1.intValue(); System.out.println(i1 + 1); //输出为13 }
JDK 5.0 新特性:自动装箱与自动拆箱
-
自动装箱:
int num2 = 10;
Integer in1 = num2;
-
自动拆箱:
int num3 = int1;
基本数据类型、包装类 -----> String类型
-
方式 ① : 连接运算。
eg: Stirng str1 = num1 + " ";
-
方法 ② : 调用String重载的valueOf(Xxx xxx)。
eg:
float f1 = 12.3f;
String str2 = String.valueOf(f1);
String类型 —> 基本数据类型、包装类。
-
错误的情况:
int num1 = (int)str1;
Integer in1 = (Integer)str1;
强制转换一定要有子父类关系,没有关系不可强转。
-
调用包装类的parseXxx()
eg:String str1 = “123”;
int num2 = Integer.parseInt(str1);
System.out.println(num2 + 1);
//输出的为124
包装类面试题:
① ? : 三元运算符中直接编译时就进行了自动类型提升。
② Integer 内部定义了IntegerCache结构,IntegerCache中定义了Integer[](数组),保存了从-128127范围内的整数。如果我们使用自动装箱的方式,给Integer赋值的范围在-128127范围内,可以直接使用数组中的元素,不用再去new了。(也就是说 == 两个相同的范围内的数时,结果是true,因为地址相同。)