- 包装类的常规操作
-
包装类常量:MAX_VALUE, MIN_VALUE, SIZE(在内存中占多少)
-
包装类构造器:接受自己的类型或者String类型,但Character除外。Integer(int val){ } Integer(String e){ } 。
-
装箱和拆箱,实现基本类型和包装类型的转换。
1 //装箱 2 Integer num1=new Integer(1111); 3 Integer num2=Integer.valueOf(222);//recommended,带有缓存 4 //拆箱 5 int a=num1.intValue();//byteValue, shortValue, integerValue,floatValue,longValue,doubleValue
4. Number()类具有byteValue, shortValue, integerValue,floatValue,longValue,doubleValue这六类方法,将当前对象转换成xxx类型,例如:
11 Long num=123L; 22 int b=num.intValue(); 33 System.out.println(b);
5. String 和包装
1 1 //String 转成包装类对象 2 2 Integer num3=new Integer("111"); 3 3 Integer num4=Integer.valueOf("222"); 4 4 System.out.println(num3+num4);//333 5 5 //包装类转成String 6 6 String str=num3.toString(); 7 7 System.out.println(str.getClass());//class java.lang.String 8 8 String str2="2222"; 9 9 int c=Integer.parseInt(str2); 1010 System.out.println(c); 1111 1212 System.out.println(new Boolean("SB"));//除了true/TRUE字符串,其他都是false.
- 包装类中的缓存设计(享元模式)
- IntegerCache是Integer中的内部类,其范围在-128-127之间。Integer.valueOf的大小判断,如果传入的数值在-127-127之间,则直接比较大小,如果超过这个范围,那么会新构建一个Integer。具体的比较可以参考这篇文章:https://www.jianshu.com/p/9cb9c61b0986
个人测试一下,结果如下:
1 1 Integer i1=new Integer(111); 2 2 Integer i2=new Integer(111); 3 3 System.out.println(i1==i2);//false 4 4 Integer i3=Integer.valueOf(123); 5 5 Integer i4=Integer.valueOf(123); 6 6 System.out.println(i3==i4);//true 7 7 Integer i5=123; 8 8 Integer i6=123; 9 9 System.out.println(i5==i6);//true 1010 //----------------------------------- 1111 Integer i_1=new Integer(222); 1212 Integer i_2=new Integer(222); 1313 System.out.println(i_1==i_2);//false 1414 Integer i_3=Integer.valueOf(222); 1515 Integer i_4=Integer.valueOf(222); 1616 System.out.println(i_3==i_4);//false 1717 Integer i_5=222; 1818 Integer i_6=222; 1919 System.out.println(i_5==i_6);//false
2. 明确一点:Integer num=xxxx是语法糖,在底层实现还是用valueOf实现的。相当于:Integer num=Integer.valueOf()。那么既然通过valueOf实现,就要按照传入参数范围判断-128-127之间。
如果不在这个范围,则新建一个Integer对象,那么通过==对比的则是对象的内存地址,所以必然每新建一个对象,这两个对象不相等。
3. 用于节省空间,共享一个,缓存设计。
4. equals也可以进行比较,但是在底层是拆箱之后比较的,所以是相等的。故,所有的包装类比较数值的时候,建议用equals。
1 System.out.println(i_5.equals(i_6));//true
- 包装类型和基本数据类型的区别,以int和Integer为例:
- Integer和Int的默认值不同,Integer为null, int为0。所以,Integer既可以表示0,也可以表示Null
- 包装类中提供了很多类型相关的算法,例如二进制转换等。Integer.tobinaryString(int val)。
- 方法中的基本类型变量存在栈中,包装类型存在堆中。
- 集合框架中,只能存放存储对象类型,不能存放基本数据类型。
- 抽象方法
- 使用abstract修饰符修饰父类(抽象类)的方法,且没有方法体
- 修饰符不能static(static 类级别的,不允许覆盖的), private(无法继承)和final(final 不允许覆盖)
- 不能创建实例,不能new一个新的对象
- 抽象类中可以不存在抽象方法,但是这样设计意义不大。