包装类:
- 基本数据类型,使用起来非常方便,但是没有对应的方法来操作这些基本类型的数据
- 可以使用一个类,把基本类型的数据装起来,在类中定义一些方法,这个类叫做包装类
- 我们可以使用类中的方法来操作这些基本类型的数据
装箱:把基本类型的数据,包装到包装类中(基本类型的数据—>包装类)
此处用int类型的包装类Integer举例
构造方法:
- Integer(int value) :构造一个新分配的 Integer对象,该对象表示指定的 int值。
- Integer(String s) : 构造一个新分配 Integer对象,表示 int由指示值 String参数。
静态方法:
- public static Integer valueOf(int i):返回一个Integer指定的int值的Integer实例。
- public static Integer valueOf(String s):返回一个Integer物体保持在指定的值String。
拆箱:在包装类中取出基本类型的数据(包装类—>基本类型的数据)
成员方法:
- public int intValue():将 Integer的值作为 int返回
//装箱:把基本类型的数据,包装到包装类中
//Integer类的构造方法
Integer num1 = new Integer(10);//参数传递一个int整数
System.out.println(num1);//10
Integer num2 = new Integer("10");//参数传递一个十进制表示形式的字符串
System.out.println(num2);//10
//静态方法
Integer num3 = Integer.valueOf(10);//参数传递一个int整数
System.out.println(num3);//10
Integer num4 = Integer.valueOf("10");//参数传递一个十进制表示形式的字符串
System.out.println(num4);//10
//拆箱:
//成员方法
int i = num1.intValue();
System.out.println(i);//10
自动装箱与自动拆箱:基本类型的数据和包装类之间可以自动的相互转换
- JDK1.5之后出现的新特性
//自动装箱:直接把int类型的整数赋值包装类
// Integer num = 1,相当于 Integer num = new Integer(1);
Integer num = 1;
//自动拆箱:num是包装类对象,无法直接参与运算,可以自动转换为基本数据类型,在进行计算
//num+2,就相当于, num.valueOf() + 2 = 3
//把 3 赋值给 num 又是一个自动装箱
num = num+2;
//list集合无法直接存储整数,可以存储Integer包装类
ArrayList<Integer> list = new ArrayList<>();
list.add(5);//-->自动装箱 list.add(new Integer(5))
int a = list.get(0);//-->自动拆箱 list.get(0).intValue();
基本类型与字符串类型之间的相互转换:
基本类型–>字符串(String)
-
1.基本类型的值+ " "最简单的方法(工作中常用)
-
2.包装类的静态方法toString(参数),不是object类的toString()重载
static String toString(int i ):返回一个表示指定整数的String对象。 -
3.String类的静态方法valueOf(参数)
static String valueOf(int i ):返回int参数的字符串表示形式
字符串(String)–>基本数据类型
使用包装类的静态方法parseXxx(“字符串”)
- Integer类: static int parseInt(String s)
- Double类: static double parseDouble(String s)
//基本数据类型--->字符串
int num1 = 100;
String str1 = num1+"";
System.out.println(str1+100);//100100
//使用包装类的toString方法
String str2 = Integer.toString(100);
System.out.println(str2+100);//100100
//使用String类的静态方法vaLueOf
String str3 = String.valueOf(100);
System.out.println(str3+100);//100100
//字符串-->基本数据类型
//使用包装类的静态方法,parseXxx
int i = Integer.parseInt(str1);
double d = Double.parseDouble(str1);
System.out.println(i+100);//200
System.out.println(d+100);//200.0
对于操作包装类的一些方法还有很多,以上只是列举了一部分,具体翻阅API文档