包装类
java 的包装类有:Byte、 Short、Integer、Long、Float、Double、Character、Boolean
装箱和拆箱
装箱是简单类型变为包装类型
拆箱是包装类型变为简单类型
public class Test{
public static void main(String[] args{
int i =10;
Integer i0 = Integer.valueOf(i);//装箱
System.out.println(i0);
double j = i0.doubleValue();//拆箱
System.out.println(j);
}
}
装包的时候会有一个缓存,在[-128,127]的数字,在第一次存储的是,会缓存到一个叫做cache的数组当中。当第二次去拿的时候,拿到的就是缓存里面的数据。但是不在上面的区间的时候,会每次产生新的对象的。
public class Test {
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
Integer c = 200;
Integer d = 200;
System.out.println(a==b); //true
System.out.println(c==d); //false
}
}
自动装箱和自动拆箱
自动装箱和自动拆箱是工作在编译期间的一种机制。
public class Test{
public static void main(String[] args{
int i=30;
Integer a = i; //自动装箱
Integer b = (Integer)i; //自动装箱
double j = a; //自动拆箱
double k = (double)a; //自动拆箱
System.out.println(a);
System.out.println(b);
System.out.println(j);
System.out.println(k);
}
}