Java 自动装箱和拆箱那些事

1.JAVA的基本数据类型

在Java中,数据类型可以分为两大种,Primitive Type(基本类型)和Reference Type(引用类型)。基本类型的数值不是对象,不能调用对象的toString()、hashCode()、getClass()、equals()等方法。所以Java提供了针对每种基本类型的包装类型。如下:

Java基本数据类型
INDEX基本类型 大小数值范围默认值包装类型
1boolean   ---true,falsefalseBoolean
2byte8bit-2^7 -- 2^7-10Byte
3char16bit
\u0000 - \uffff
\u0000Character
4short16bit-2^15 -- 2^15-10Short
5int 32bit-2^31 -- 2^31-10Integer
6long64bit-2^63 -- 2^63-10Long
7float 32bitIEEE 7540.0fFloat
8double 64bitIEEE 7540.0dDouble

2.浅谈拆箱与装箱

装箱是将一个原始数据类型赋值给相应封装类的变量。而拆箱则是将一个封装类的变量赋值给相应原始数据类型的变量。

Java 1.5中引入了自动装箱和拆箱机制:

       (1)自动装箱:把基本类型用它们对应的引用类型包装起来,使它们具有对象的特质,可以调用toString()、hashCode()、getClass()、equals()等方法。

        如下:

        Integer a=3;//这是自动装箱

        其实编译器调用的是static Integer valueOf(int i)这个方法,valueOf(int i)返回一个表示指定int值的Integer对象,那么就变成这样: 

        Integer a=3;   =>    Integer a=Integer.valueOf(3);

1 public static Integer valueOf(inti) {    
2     if(i >= -128 &&i <=IntegerCache.high)    
3        //如果i在-128~high之间,就直接在缓存中取出i的Integer类型对象  
4        return IntegerCache.cache[i + 128];    
5     else  
6        return new Integer(i); //否则就在堆内存中创建   
7 }    

 

        (2)拆箱:跟自动装箱的方向相反,将Integer及Double这样的引用类型的对象重新简化为基本类型的数据。

         如下:

         int i = new Integer(2);//这是拆箱

         编译器内部会调用int intValue()返回该Integer对象的int值

       

1     public int intValue() {  
2          return value;  
3     } 

 

         注意:自动装箱和拆箱是由编译器来完成的,编译器会在编译期根据语法决定是否进行装箱和拆箱动作。

 java定义:在自动装箱时对于值从–128到127之间的值,它们被装箱为Integer对象后,会存在内存中被重用,始终只存在一个对象 
     而如果超过了从–128到127之间的值,被装箱后的Integer对象并不会被重用,即相当于每次装箱时都新建一个 Integer对象;

  1. Integer i1=100;  
  2. Integer i2=100;  
  3. Integer i3=300;  
  4. Integer i4=300;  
  5. System.out.println(i1==i2);  
  6. System.out.println(i3==i4);  

运行结果为“System.out.println(i1==i2);”为 true,但是“System.out.println(i3==i4);”为false。也就意味着,i1与i2这两个Integer类型的引用指向了同一个对象,而i3与i4指向了不同的对象。为什么呢?不都是调用Integer.valueOf(int i)方法吗?

1 public static Integer valueOf(inti) {    
2     if(i >= -128 &&i <=IntegerCache.high)    
3        //如果i在-128~high之间,就直接在缓存中取出i的Integer类型对象  
4        return IntegerCache.cache[i + 128];    
5     else  
6        return new Integer(i); //否则就在堆内存中创建   
7 }    

     我们可以看到当i>=-128且i<=IntegerCache.high时,直接返回IntegerCache.cache[i + 128]。其中,IntegerCache为Integer的内部静态类,其原码如下:

 1 private static class IntegerCache {//内部类,注意它的属性都是定义为static final  
 2     static final inthigh; //缓存上界  
 3     static final Integer cache[];//cache缓存是一个存放Integer类型的数组  
 4   
 5     static {//静态语句块  
 6         final int low = -128;//缓存下界,值不可变  
 7   
 8         // high value may beconfigured by property  
 9         int h = 127;// h值,可以通过设置jdk的AutoBoxCacheMax参数调整(参见(3))  
10         if (integerCacheHighPropValue !=null) {  
11             // Use Long.decode here to avoid invoking methods that  
12             // require Integer's autoboxing cache to be initialized  
13             // 通过解码integerCacheHighPropValue,而得到一个候选的上界值  
14             int i = Long.decode(integerCacheHighPropValue).intValue();  
15             // 取较大的作为上界,但又不能大于Integer的边界MAX_VALUE  
16             i = Math.max(i, 127);//上界最小为127  
17             // Maximum array size is Integer.MAX_VALUE  
18             h = Math.min(i, Integer.MAX_VALUE - -low);  
19         }  
20         high = h; //上界确定,此时high默认一般是127  
21         // 创建缓存块,注意缓存数组大小  
22         cache =new Integer[(high - low) + 1];  
23         int j = low;  
24         for(int k = 0; k <cache.length; k++)  
25             cache[k] =new Integer(j++);// -128到high值逐一分配到缓存数组  
26     }  
27   
28     private IntegerCache() {}//构造方法,不需要构造什么  
29 }  

          我们可以清楚地看到,IntegerCache有静态成员变量cache,为一个拥有256个元素的数组。在IntegerCache中也对cache进行了初始化,即第i个元素是值为i-128的Integer对象。而-128至127是最常用的Integer对象,这样的做法也在很大程度上提高了性能。也正因为如此,“Integeri1=100;Integer i2=100;”,i1与i2得到是相同的对象。

          对比扩展中的第二个实验,我们得知,当封装类与基础类型进行==运行时,封装类会进行拆箱,拆箱结果与基础类型对比值;而两个封装类进行==运行时,与其它的对象进行==运行一样,对比两个对象的地址,也即判断是否两个引用是否指向同一个对象。

扩展:

getAndRemoveCacheProperties方法,用于获取或移除JDK对Integer设置的缓存属性,同时可以通过调整虚拟机-XX:AutoBoxCacheMax=<size>选项,调整“自动装箱池”的大小 

 1 private static String integerCacheHighPropValue;  
 2 static void getAndRemoveCacheProperties() {  
 3     if (!sun.misc.VM.isBooted()) {  
 4         Properties props= System.getProperties();  
 5         integerCacheHighPropValue=  
 6             (String)props.remove("java.lang.Integer.IntegerCache.high");  
 7         if (integerCacheHighPropValue!=null)  
 8             System.setProperties(props); // remove from system props  
 9      }  
10  }  

设置-XX:AutoBoxCacheMax=<size>

         在eclipse中,选中源文件,右键Run as—>RunConfiguratio--->Arguments,在VM arguments中做以下设置:

          

转载于:https://www.cnblogs.com/xiaoqing2013/p/4159410.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值