Java为每种基本数据类型都提供了对应的包装器类型,在jdk1.5之前,声明一个包装类需要这样写:
Integer i = new Integer(10);
而从1.5以后提供了自动装箱拆箱的功能,就可以这样写了:
Integer i = 10;
这个过程中会自动根据数值创建对应的 Integer对象,这就是装箱.
而拆箱自然也就是将包装类型转换为基本类型了:
Integer i = 10; //装箱
int n = i; //拆箱
总结一下就是:
装箱就是 自动将基本数据类型转换为包装器类型.
拆箱就是 自动将包装器类型转换为基本数据类型.
先来看一段代码:
Integer integer=null;
int int=integer;
在编译过程中,这段代码是没有问题的,但是在运行的时候会抛出空指针异常,不信可以跑一下试试.那这是怎么回事?
其实,integer为Integer类型的对象,它当然可以指向null。但在第二行时,就会对integer进行拆箱,也就是对
一个null对象执行intValue()方法,当然会抛出空指针异常。所以,有拆箱操作时一定要特别注意封装类对象是否
为null。
3.2 引用和值的问题
再来看一段代码:
Integer i1=100;
Integer i2=100;
Integer i3=300;
Integer i4=300;
System.out.println(i1==i2);
System.out.println(i3==i4);
结果是:
true
false
是不是懵逼了?其实原因也很简单,这里边涉及到一个缓存池的概念,先来介绍一下**缓存池**,之后就会明白了
new Integer(123) 与 Integer.valueOf(123) 的区别在于:
new Integer(123) 每次都会新建一个对象;
Integer.valueOf(123) 会使用缓存池中的对象,多次调用会取得同一个对象的引用。
Integer x = new Integer(123);
Integer y = new Integer(123);
System.out.println(x == y); // false
Integer z = Integer.valueOf(123);
Integer k = Integer.valueOf(123);
System.out.println(z == k); // true
valueOf() 方法的实现比较简单,就是先判断值是否在缓存池中,如果在的话就直接返回缓存池的内容。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
在 Java 8 中,Integer 缓存池的大小默认为 -128~127。
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
编译器会在自动装箱过程调用 valueOf() 方法,因此多个值相同且值在缓存池范围内的 Integer 实例使用自动装箱来创建,那么就会引用相同的对象。
Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true
基本类型对应的缓冲池如下:
boolean -- true and false
short -- -128 to 127
int -- -128 to 127
char -- \u0000 to \u007F
在使用这些基本类型对应的包装类型时,就可以直接使用缓冲池中的对象。
明白了缓存池,再回来看这个问题,i1与i2这两个Integer类型的引用指向了同一个对象,而i3与i4指向了不同的对象。为什么呢?不都是调用
Integer.valueOf(int i)方法吗?
再看Integer.valueOf(int i)方法就能明白当i>=-128且i<=IntegerCache.high时,直接返回IntegerCache.cache[i + 128]。其中,IntegerCache
为Integer的内部静态类,也就是上边的第二部分代码,我们可以清楚地看到,IntegerCache有静态成员变量cache,为一个拥有256个元素的数组。在
IntegerCache中也对cache进行了初始化,即第i个元素是值为i-128的Integer对象。而-128至127是最常用的Integer对象,这样的做法也在很大程度
上提高了性能。也正因为如此,“Integeri1=100;Integer i2=100;”,i1与i2得到是相同的对象。
什么是java的自动拆箱和拆箱?1.什么是装箱和拆箱?Java为每种基本数据类型都提供了对应的包装器类型,在jdk1.5之前,声明一个包装类需要这样写:Integer i = new Integer(10);而从1.5以后提供了自动装箱拆箱的功能,就可以这样写了:Integer i = 10;这个过程中会自动根据数值创建对应的 Integer对象,这就是装箱.而拆箱自然也就是将包装类...