Java里对于整型常量一般是放在方法区的常量池里,对于Integer包装类,使用自动装箱机制生成该类实例时,会先从缓存里查看有没有这个值,查看Integer类的源码时,发现这个类里面还有一个内部类IntegerCache,这个类的作用就是缓存**-128~127**这些常用数值,源码贴在这里,注意到里面的high字段是没有赋初始值的,而是通过静态块里的h这个变量赋值的,但是这个h又可以通过虚拟机参数设置来改变(sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"))
,具体的命令为-Djava.lang.Integer.IntegerCache.high = 1000
(这里1000是一个示例)。
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() {}
}
当调用valueOf(int i)
方法时(也就是自动装箱机制),先查看是否在此范围内,如果是,从池中返回,不是则new
一个新的对象实例,valueOf(int i)
方法源码如下,可以看到里面是用了IntegerCache
的low
字段和high
字段判断的:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
注意,如果直接使用new
创建对象,则不会从缓存中查询,因为只有valueOf(int i)
使用了这个内部类。
由于上面讲到的内容,使用自动装箱的Integer
类实例时,会发生一些有意思的事情,具体代码如下:
//未设置jvm参数时
public class AutoBoxTest {
public static void main(String[] args) {
//==比较对象时,比较的是地址
//127在默认缓存范围内,因此从常量池里取出来地址
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2);
i1 = 128;
i2 = 128;
System.out.println(i1 == i2);//这里就不是从常量池里取出来的了
}
}
//运行结果:
//true
//false
如果使用jvm
参数改变这个缓存范围时,又会出现其他的结果:
//改变jvm参数时 : -Djava.lang.Integer.IntegerCache.high = 1000
public class AutoBoxTest {
public static void main(String[] args) {
//==比较对象时,比较的是地址
//127在默认缓存范围内,因此从常量池里取出来地址
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2);
i1 = 128;
i2 = 128;
System.out.println(i1 == i2);//这里就不是从常量池里取出来的了
}
}
//运行结果:
//true
//true
多看源码,多思考,这些东西还是蛮有意思的~~
总结
1、基本型和基本型封装型进行"=="运算符的比较,基本型封装型将会自动拆箱变为基本型后再进行比较,因此Integer(0)
会自动拆箱(调用的Integer
的intValue()
方法)为int
类型再进行比较,显然返回true
;
2、两个Integer
类型进行“==”比较,比较的是这两个对象的地址是否相等;
3、两个基本型的封装型进行equals()
比较,首先equals()
会比较类型,如果类型相同,则继续比较值,如果值也相同,返回true
;
4、基本型封装类型调用equals()
,但是参数是基本类型,这时候,先会进行自动装箱,基本型转换为其封装类型,再进行3中的比较。
int a = 257;
Integer b = 257;
Integer c = 257;
Integer b2 = 57;
Integer c2 = 57;
System.out.println(a == b);
System.out.println(b.equals(257.0));
System.out.println(b == c);
System.out.println(b2 == c2);
//运行结果:
//true
//false
//false
//true