包装类的缓存问题

缓存问题

缓存处理的原理为:如果数据在-128~127这个区间,那么在类加载时就已经为该区间的每个数值创建了对象,并将这256个对象存放到一个名为cache的数组中。每当自动装箱过程发生时(或者手动调用valueOf()时),就会先判断数据是否在该区间,如果在则直接获取数组中对应的包装类对象的引用,如果不在该区间,则会通过new调用包装类的构造方法来创建对象。

代码

这里用Integer包装类来进行演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Cache {

public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* 这里会进行自动装箱,JDK在1.5以后可以这样写
*/
Integer a = 10; //Integer a = Integer.valueOf(10);
Integer b = 10; //Integer b = Integer.valueOf(10);
System.out.println(a==b); //输出 true
Integer c = 129;
Integer d = 129;
System.out.println(c==d); //输出false
/**
* 自动拆箱
*/
int e = a; //int e = a.intValue(); int e =new Integer(a);
}

}

自动装箱代码

1
2
3
4
5
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

自动拆箱代码

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

额外内容

  1. JDK1.5以后,增加了自动装箱与拆箱功能。

  2. 自动装箱调用的是valueOf()方法,而不是new Integer()方法。

  3. 自动拆箱调用的xxxValue()方法。

  4. 包装类在自动装箱时为了提高效率,对于-128~127之间的值会进行缓存处理。超过范围后,对象之间不能再使用==进行数值的比较,而是使用equals方法。

原创技术分享,您的支持将鼓励我继续创作
0%