包装类型、缓存池
- 每个基本类型都有对应的包装类型,基本类型与其对应的包装类型之间的赋值使用自动装箱与拆箱完成
缓存池
new Integer(123)与Integer.valuesOf(123)的区别
- new Integer(123)每次都会新建一个对象
- Integer.valuesOf(123)会使用缓存池中的对象,多次调用会取得同一个对象的引用
看代码之前我们先来了解一下Java中==的作用
- 比较基本类型时,==的作用是比较双方的值
- 比较对象类型时,==是指向双方的对象是否相同(这里对比的对象是指new出来的一个对象存在JVM中的地址值,而不是说对比Integer和Integer对象是都相同),对象的地址相同之后再比较值是否相同
回到原来的话题,对比new Integer(123)与Integer.valuesOf(123)的区别
public class test {
public static void main(String[] args) {
Integer a = new Integer("123");
Integer b = new Integer("123");
System.out.println(a == b); //false
Integer c = Integer.valueOf(123);
Integer d = Integer.valueOf(123);
System.out.println(c == d); //true
Integer e = Integer.valueOf(144);
Integer f = Integer.valueOf(144);
System.out.println(e == f); //false
}
}
那么问题来了,同样都是valueOf()方法,为什么cd的返回值是true,而ef的返回值是false
这里引出一个缓存池大小的说法
Integer的缓存池大小默认是-128—127
使用valueOf()方法时,会先判断值是否再缓存池中,如果在的话,直接返回缓存池中的内容,如果不在缓存池范围内,则会new一个出来
可以从Integer类的代码中看出
public static Integer valueOf(int i) { //i的大小在low --- high之间
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
private static class IntegerCache { //这里可以看出系统定义的low为-128,high为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;
}
private IntegerCache() {}
}
基本类型对应的缓冲池如下
- boolean values true and false
- all byte values
- short values between -128 and 127
- int values between -128 and 127
- char in the range \u0000 to \u007F
在 jdk 1.8 所有的数值类缓冲池中,Integer 的缓冲池 IntegerCache 很特殊,这个缓冲池的下界是 - 128,上界默认是 127,但是这个上界是可调的,在启动 jvm 的时候,通过 -XX:AutoBoxCacheMax= 来指定这个缓冲池的⼤⼩,该选项在 JVM 初始化的时候会设定⼀个名为 java.lang.IntegerCache.high 系统属性,然后 IntegerCache 初始化的时候就会读取该系统属性来决定上 界。