自动装箱与自动拆箱

来源:互联网 发布:手机汽车设计软件 编辑:程序博客网 时间:2024/06/11 19:59

什么是自动装箱和拆箱

自动装箱就是Java自动将基本类型值转换成对应的对象,比如将int的变量转换成Integer对象,这个过程叫做装箱,反之将Integer对象转换成int类型值,这个过程叫做拆箱。因为这里的装箱和拆箱是自动进行的非人为转换,所以就称作为自动装箱和拆箱。基本类型和包装类之间的对应关系 : 
这里写图片描述

自动装箱拆箱要点

自动装箱时编译器调用valueOf将基本类型值转换成对象,同时自动拆箱时,编译器通过调用类似intValue(),doubleValue()这类的方法将对象转换成基本类型值 

装箱:把基本类型转换成包装类,使其具有对象的性质,又可分为手动装箱和自动装箱

 

拆箱:和装箱相反,把包装类对象转换成基本类型的值,又可分为手动拆箱和自动拆箱

 


注意事项

这是一个比较容易出错的地方,”==“可以用于原始值进行比较,也可以用于对象进行比较,当用于对象与对象之间比较时,比较的不是对象代表的值,而是检查两个对象是否是同一对象,这个比较过程中没有自动装箱发生。进行对象值比较不应该使用”==“,而应该使用对象对应的equals方法。看一个能说明问题的例子。
public class AutoboxingTest {    public static void main(String args[]) {        // Example 1: == comparison pure primitive – no autoboxing        int i1 = 1;        int i2 = 1;        System.out.println("i1==i2 : " + (i1 == i2)); // true        // Example 2: equality operator mixing object and primitive        Integer num1 = 1; // autoboxing        int num2 = 1;        System.out.println("num1 == num2 : " + (num1 == num2)); // true        // Example 3: special case - arises due to autoboxing in Java        Integer obj1 = 1; // autoboxing will call Integer.valueOf()        Integer obj2 = 1; // same call to Integer.valueOf() will return same                            // cached Object        System.out.println("obj1 == obj2 : " + (obj1 == obj2)); // true        // Example 4: equality operator - pure object comparison        Integer one = new Integer(1); // no autoboxing        Integer anotherOne = new Integer(1);        System.out.println("one == anotherOne : " + (one == anotherOne)); // false        System.out.println("i2 == anotherOne : " + (i2 == anotherOne)); // true        System.out.println("obj1 == anotherOne : " + (obj1 == anotherOne)); // false    }}Output:i1==i2 : truenum1 == num2 : trueobj1 == obj2 : trueone == anotherOne : false
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

值得注意的是第三个小例子,这是一种极端情况。obj1和obj2的初始化都发生了自动装箱操作。但是处于节省内存的考虑,JVM会缓存-128到127的Integer对象。因为obj1和obj2实际上是同一个对象。所以使用”==“比较返回true。


原创粉丝点击