包装类是一种java常用开发类 包装类对应8大基本类型 网上搜索一下就好了
案例1
public static void main(String[] args) {
System.out.println("----包装类常用属性-------------");
System.out.println(Integer.MAX_VALUE); //对应基本类型的最大值
System.out.println(Integer.MIN_VALUE); //对应基本类型的最小值
System.out.println(Integer.TYPE); //对应的基本类型
System.out.println("---------包装类中的常用方法---------");
//[1] 把String类型转换成int类型
String str = "123";
int num = Integer.parseInt(str);
//[2]把String类型转换成Integer
Integer integer = Integer.valueOf(str);
//[3]把Integer类型转化成String
String s = integer.toString();
System.out.println("-----------手动装箱和拆箱-------------");
int a =10;//基本数据类型
Integer integer1 = new Integer(a);//手动装箱:把基本类型变成对应的包装类
int i = integer1.intValue();//手动拆箱:把包装类转成对应的基本数据类型
System.out.println("-----------JDK1.5以后的自动装箱和拆箱---------");
int b = 10;//基本数据类型
Integer integer2 = b;//这个过程就是自动装箱 等价于Integer intger = new Integer(b)
int i2 = integer2;
System.out.println("------------隐藏的装箱和拆箱-----------------");
Integer c = new Integer(10);
c++; //此时c为基本数据类型 jdk偷偷拆箱了 把c的包装类转换成基本数据类型了
Integer bb = 10;
int cc = 10;
bb.equals(cc); // 此时cc为Integer类型 jdk底层把cc基本数据类型转换成包装类了
}
案例2 要注意的细节
public static void main(String[] args) {
int a =10;
Integer b = 10;
System.out.println(a==b); //ture[+ - * / ==] 这些属于基本数据类型的运算 自动拆箱 b拆箱成基本数据类型 所以 == 比较的不是地址值了 而是比较值
System.out.println(b.equals(a));//ture 自动装箱 a装箱成包装类
Integer a2 = new Integer(10); //new关键字申请新的空间
Integer b2 = new Integer(10); // new关键字申请了新的空间
System.out.println(a2==b2); //比较的是地址 false
System.out.println(b2.equals(a2)); //比较的是值 ture
Integer a3 = 10; //自动装箱 调用了一个.valueOf方法 valueOf有个缓存数组存储了-128到127值 如果要装箱的值不在缓存数组范围内 就直接把要包装的值对应的地址返回了 并没有开辟新的空间地址
Integer b3 = 10;
System.out.println(a3 == b3); //ture a3为常量10
System.out.println(a3.equals(b3));//ture
Integer a4 = 200;
Integer b4 = 200;
System.out.println(a4 == b4); //false 超出了valueOf缓存数组 返回new Integer类型
System.out.println(a4.equals(b4)); //true
}