Java知识点梳理——装箱和拆箱

1、前言:Java是典型的面向对象编程语言,但其中有8种基本数据类型不支持面向对象编程,基本数据类型不具备对象的特性,没有属性和方法;Java为此8种基本数据类型设计了对应的类(包装类),使之相互转换,间接实现基本数据类型具备对象特性,丰富基本数据类型操作;

基本数据类型 包装类
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean


 

 

 

 

 

 

 

 

 

 


 注:int是基本数量类型,Integer是类;int和Ingeger初始值不同(int默认值0 Ingeger默认值null);Integer包含属性和方法,int则没有;基本数据类型和包装类相互转换的过程叫装箱和拆箱;

2、装箱:基本数据类型转换成对应的包装类(int——>Integer);

1 Integer i = new Integer(10); // 手动装箱
2 Integer i = 10; // 自动装箱

3、拆箱:包装类转换成基本数据类型(Integer——>int);

1 Integer i =10; // 自动装箱
2 int m = i; // 自动拆箱
3 int n = i.intValue(); // 手动拆箱

4、自动装箱和自动拆箱:Java 1.5以后才有自动装箱、拆箱的特性;自动装箱是通过包装类的valueOf方法实现;自动拆箱是通过包装类的xxxValue方法实现

1 Integer i = Integer.valueOf(10); // 调用valueOf方法自动装箱
2 int n = i.intValue(); // 调用intValue方法自动拆箱

 注:自动装箱会隐式地创建对象,在一个循环中注意自动装箱问题,影响程序性能;

5、equals 和 == 比较:当 "=="运算符的两个操作数都是包装类,则是比较指向的是否是同一个对象,而如果其中有一个操作数是表达式(即包含算术运算)则比较的是数值(触发自动拆箱);对于包装类,equals方法不会进行类型转换

 1 public class Main {
 2     public static void main(String[] args) {
 3          
 4         Integer a = 1;
 5         Integer b = 2;
 6         Integer c = 3;
 7         Integer d = 3;
 8         Integer e = 321;
 9         Integer f = 321;
10         Long g = 3L;
11         Long h = 2L;
12          
13         System.out.println(c==d); // true
14         System.out.println(e==f); // false
15         System.out.println(c==(a+b)); // true
16         System.out.println(c.equals(a+b)); // true
17         System.out.println(g==(a+b)); // true
18         System.out.println(g.equals(a+b)); // false
19         System.out.println(g.equals(a+h)); // true
20     }
21 }

 解析:JVM会缓存-128到127的Integer对象(Short、Byte、Character、Long与Integer类似),所以第一个是同一个对象true,第二个是new的新对象false;第三个有+法运算比较的是两边的值true;第四个有+法运算且两边的数据类型相同true;第五个同四先求+法求和 ,==会进行类型转换(Long)true;第六个先+法求和,equals不会类型转换false;第七个先+法求和(触发拆箱,变成了int类型和long类型相加,这个会触发类型晋升,结果是long类型的)equals比较时触发装箱比较两边都是Long类型结果true;

 

posted @ 2018-07-26 11:54  蜡笔小嘻  阅读(346)  评论(0编辑  收藏  举报