一、什么是包装类?
The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.
In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.
包装类是基本数据类型对应的引用类型。
二、为什么要学包装类?
现在很多方法都是用多态的方式来接收参数,基本数据类型的参数传不进来,并且集合也只能存储引用类型的数据。
三、包装类的类型
四、装箱和拆箱
基本类型与对应的包装类对象之间,来回转换的过程称为“装箱”与“拆箱”。
- 装箱:从基本数据类型转换为对应的包装类对象
- 拆箱:从包装类对象转换为对应的基本数据类型
代码演示:
package io.github.wangpeng;
public class WrapperClassDemo {
public static void main(String[] args) {
// 1、构造方法创建包装类对象 装箱
Integer integer1 = new Integer(8);
// 重写了toString方法
System.out.println(integer1);
// 2、静态方法创建包装类对象 装箱
Integer integer2 = Integer.valueOf(8);
System.out.println(integer2);
Integer integer3 = Integer.valueOf("8");
System.out.println(integer3);
// 3、拆箱:从包装类中取出基本类型的数据
int i = integer1.intValue();
System.out.println(i);
}
}
五、自动装箱和拆箱
JDK1.5之后新增了新特性,也就是基本类型的数据和包装类之间可以自动的相互转换。
package io.github.wangpeng;
public class WrapperClassDemoAutomatic {
public static void main(String[] args) {
// 自动装箱:直接把int类型的数据赋值给包装类
Integer integer = 1;
// 自动拆箱:包装类对象无法直接参与运算,可以自动转换为基本数据类型,再参与运算
integer = integer + 8;
System.out.println(integer);
}
}
六、Integer类中的方法
package io.github.wangpeng;
public class WrapperClassMethod {
public static void main(String[] args) {
// public static String toBinaryString(int i)
// 1.将整数转换为二进制
String s = Integer.toBinaryString(100);
System.out.println(s); // 1100100
// public static String toOctalString(int i)
// 2.将整数转换为八进制
String s1 = Integer.toOctalString(100);
System.out.println(s1); // 144
// public static String toHexString(int i)
// 3.将整数转换为十六进制
String s2 = Integer.toHexString(100);
System.out.println(s2); // 64
// public static int parseInt(String s)
// 4.将字符串类型的整数转换成int类型的整数
int i = Integer.parseInt("123");
System.out.println(i + 1); // 124
}
}