基本类型包装类
primitive主数据类型的包装
除了int 和 char 数据类型的包装类 为 Integer 和 Character 外
其余包装类都是 首字母大写。
装箱和拆箱的操作
例: 包装一个int 型
int i = 8;
Integer a = new Integer(i);
调用包装类的构造方法。 包装给 Integer 的实例
拆箱
int a = a.intvalues();
转为基本数据类型。
为什么要完成基本数据类型的包装?
在集合中 是要用到泛型类的 而泛型的规则是 你只能传入类。
这就说明:定义一个数组容器类 ArrayList<int> 是不能通过编译的。这就需要定义为 ArrayList<Integer>
JDK的自动装箱和拆箱
有了自动装箱和拆箱的功能
我们就可以在ArrayList<Integer> 中 传入相应的int 型 编译器并不会报错 编译器会自动帮你完成自动装箱的操作 也就是说 基本数据类型和包装类之间可以相互转换 这就是自动装箱和拆箱的好处所在。
包装类使用时候的注意条件
public class Static {
Integer a;
int b;
public static void main(String[] args) {
new Static().go();
}
void go(){
b = a;
System.out.println(a);
System.out.println(b);
}
}
这里会报出一个错误:Cannot invoke “java.lang.Integer.intValue()” because “this.a” is null
对象的引用为空。 这里要注意的是 Integer 是个类 a 是一个引用
要么你完成对象的创建 要么赋值让他进行自动装箱。
包装类的奇妙之处
它可以用来做算数运算。
但要注意给对象”赋值“。
包装类的静态实用性方法
类型之间的转换
例子:
Integer.parseInt(String) : 方法。
String s = "2";
int x = Integer.parseInt(s);
将 "2" 转换为 2
但是 s == "two" 就不行了
会抛出运行时的NumberFormat异常。