49

Java自动装箱-拆箱机制究竟是什么

 5 years ago
source link: https://tryenough.com/java-autobox?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

自动装箱和拆箱从Java 1.5开始引入,目的是将原始类型值转自动地转换成对应的对象。

什么是自动装箱和拆箱

自动装箱就是Java自动将原始类型值转换成对应的对象,比如将int的变量转换成Integer对象,这个过程叫做装箱,反之将Integer对象转换成int类型值,这个过程叫做拆箱。

原始类型byte,short,char,int,long,float,double和boolean对应的封装类为Byte,Short,Character,Integer,Long,Float,Double,Boolean。

何时发生自动装箱和拆箱

比如我们有一个方法,接受一个对象类型的参数,如果我们传递一个原始类型值,那么Java会自动讲这个原始类型值转换成与之对应的对象。

ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(1); //自动装箱 - primitive to object
intList.add(2); //自动装箱

ThreadLocal<Integer> intLocal = new ThreadLocal<Integer>();
intLocal.set(4); //自动装箱

int number = intList.get(0); // 拆箱
int local = intLocal.get(); // 拆箱

Java 1.5以前我们需要手动地进行转换才行,而现在所有的转换都是由编译器来完成

//Java 1.5以前
Integer iObject = Integer.valueOf(3);
Int iPrimitive = iObject.intValue()

//Java 1.5之后
Integer iObject = 3; //自动装箱 - primitive to wrapper conversion
int iPrimitive = iObject; //拆箱 - object to primitive conversion

自动装箱的弊端

在一个循环中进行自动装箱操作,会创建多余的对象,影响程序的性能。

Integer sum = 0;
 for(int i=1000; i<5000; i++){
   sum+=i;
}

sum = sum + i,但是+这个操作符不适用于Integer对象,首先sum进行自动拆箱操作,进行数值相加操作,最后发生自动装箱操作转换成Integer对象。其内部变化如下

int result = sum.intValue() + i;
Integer sum = new Integer(result);

上面的循环中会创建将近4000个无用的Integer对象,浪费了性能。

生成无用对象增加GC压力,在写循环时一定要注意代码,避免引入不必要的自动装箱操作。

热度: 7


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK