深入理解Java的自动装箱和拆箱
自动装箱和拆箱是从Java 1.5开始引入的,在Java语言规范中说道:在许多情况下包装(装箱)与解包装(拆箱)是由编译器自行完成的,那么问题来了,为什么要多此一举自动拆箱与装箱呢?简单点不好吗?以我个人的理解是——
为什么需要装箱和拆箱
装箱:因为Java提倡的是面对对象,万物皆对象,所以自动装箱就可以简单的理解为将基本数据类型封装为对象类型,这么一来呢就更符合java的面向对象思想
拆箱:为了适用基本数据类型的使用场景
装箱原理:
简单的理解是——编译器调用:Integer integer = new Integer(int i);帮我们把基本数据类型包装成了对象。
Integer integer = 10;
//等价于
Integer intege = new Integer(10);
其实还有更复杂的,对象时一定会创建的,但是如何创建,水很深!我决定在另一篇博客说明这件事情!!!Integer对象隐藏的面试题 (链接)
拆箱原理
编译器调用Integer 对象的intValue()方法
/**
* Returns the value of this {@code Integer} as an
* {@code int}.
*/
public int intValue() {
return value;
}
这个value哪里来的呢,源码中是把它定义在Integer类中,且是一个私有不可更改的成员变量
/**
* The value of the {@code Integer}.
*
* @serial
*/
private final int value;
然后在构造函数中初始化了它
/**
* Constructs a newly allocated {@code Integer} object that
* represents the specified {@code int} value.
*
* @param value the value to be represented by the
* {@code Integer} object.
*/
public Integer(int value) {
this.value = value;
}