在Java中,Integer
类有一个缓存池机制,用于缓存一定范围内的Integer
对象。
package 包装;
public class Demo3 {
public static void main(String[] args) {
//只要有new 就会开辟空间
Integer i1=new Integer(127);
Integer i2=new Integer(127);
System.out.println(i1==i2);
//Integer类的内部,维护了一个IntegerCache缓存池
// 将 -128至127之间所有的数字进行了缓存
Integer i3=Integer.valueOf(129); //数值不在缓存池范围内,新建,分配新的内存空间
Integer i4=Integer.valueOf(129); //数值不在缓存池范围内,新建,分配新的内存空间
System.out.println(i3==i4);
//equals比较内容
System.out.println(i1.equals(i2));
System.out.println(i3.equals(i4));
}
}
在这个例子中,i1和i2都被赋值为127,而i3和i4都被赋值为129。
通过==运算符比较它们的引用时,i1==i2返回true i3==i4则返回false。这是因为Integer类在缓存池中缓存了-128到127之间的整数
因为i1和i2实际指向了缓存池中的同一个对象 而i3和i4超出了缓存范围 因为他们是两个不同的对象
在Integer类的源代码中,缓存池的定义可以在IntegerCache类中找到,以下是Integer的关键源码
private static class IntegerCache {
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;
}
private IntegerCache() {}
}
low和high定义了缓存池的范围,默认情况下low为-128,high为127.
cache是一个Integer数组 用于存储缓存的对象
在静态初始化中 cache数组别初始化 并且从low到high的每个整数都别缓存为一个Integer对象
Integer.valueOf(int i)方法是使用缓存池的主要方式。与直接使用new Integer(int i)创建对象不一样
valueOf方法会首先检查传入的整数值是否在缓存池的范围内。如果在范围内,则返回缓存池的对象 如果不在范围内 则创建一个新的Integer对象
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如果i的值在缓存池的范围内 (即low到high之间),则直接从缓存池中返回对应的Integer对象
如果i的值超出了缓存池的范围 则创建一个新的Integer对象并返回
意义
性能优化:通过缓存池 Integer.valueOf()方法避免了频繁创建和销毁小范围内的Integer对象,从而提高了性能
内存节省:对于常用的整数值 缓存池减少了内存的使用 因为相同的值共享同一个对象
Integer
缓存池是Java中一个重要的优化机制,它通过缓存一定范围内的Integer
对象,减少了内存的使用并提高了性能。通过Integer.valueOf()
方法,我们可以充分利用缓存池,避免不必要的对象创建。理解这一机制对于编写高效的Java代码非常重要。