1、包装类的概念:
- 包装类是八种基本数据类型所对应的引用类型。
- 将基本数据类型变为包装类之后,基本数据类型就有了类的特点,就可以调用类中的方法。
- 包装类。都是被final修饰的,因此不能有子类。
2、包装类和基本数据类型的转换:
我们以Integer类型为例来演示拆箱和装箱
手动拆箱和装箱
//手动装箱
int n = 1;
Integer integer = Integer.valueOf(n);
System.out.println(integer);
//手动拆箱
int n1 = integer.intValue();
注意:
n的值在-127~128之间,Integer.valueOf的返回值就是n,如果不在这个范围返回的就是以n为参数创建的Integer对象。
在这个范围内,jvm会优化,将值存储在堆中。因此使用==比较的是数值,不再该范围内则比较的是对象地址。
所以包装类最好使用equals方法进行比较。
源码
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
3、 包装类型和String类型相互转换
//包装类 --> String
//方式1:将包装类的对象的值拼接字符串赋给String
Integer i = 1;
String s1 = i + "";
//方式2:包装类的对像调用toString方法
String s2 = i.toString();
//方式3:String类的value方法也是通过调用Integer的toString方法
String s3 = String.valueOf(i);
//String --> 包装类
String str = "3234";
//方式1:Integer类调用valueOf方法,valueOf(Stringstr)方法中通过parseInt方法将String类型的值
// 转为int再调用value(Int i),返回一个Integer对象
Integer integer = Integer.valueOf(str);
Integer integer1 = Integer.parseInt(str);
Integer integer2 = new Integer(str);
4、包装类的注意事项
1、包装类的value属性是被final属性修饰的,所以一大把构造了包装类,就不能修改包装在里面的值。
2、装箱和拆箱是编译器认可的,而不是虚拟机。编译器在生成类的.class文件时,插入必要的方法调用。虚拟机只是执行这些字节码。