我们都知道java中对象之间用==进行的比较是内存地址之间的比较,也就是说==比较的话,如果两个引用指向堆内存中同一个对象那么就返回true,否则返回false。
Integer对象之间的比较
首先来看一下这样一段代码:
public static void main(String[] args) {
// case 1
Integer a1 = Integer.valueOf(60);
Integer b1 = 60;
System.out.println("1:="+(a1 == b1));
// case 2
Integer a2 = 60;
Integer b2 = 60;
System.out.println("2:="+(a2 == b2));
// case 3
Integer a3 = new Integer(60);
Integer b3 = 60;
System.out.println("3:="+(a3 == b3));
// case 4
Integer a4 = 129;
Integer b4 = 129;
System.out.println("4:="+(a4 == b4));
}
读者可以仔细想一下这四种情况输出什么?
现在来公布输出结果:
1:=true
2:=true
3:=false
4:=false
是否多少有点惊讶?现在我们就对上面的四种情况一一进行分析。
case 1:
我们知道java中把基本类型赋给它的保证类型编译器会自动帮我们装箱(也就是创建一个包装类型)。创建保证类型的时候会调用Integer.valueOf(i)方法,下面我们来看一下这个方法的源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
我们会惊奇的发现当基本数据类型在IntegerCache.low和IntegerCache.high会从IntegerCache.cache中取出数据。下面我们来分析一下IntegerCache这个类:
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;
// 在配置文件中配置了high的值
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() {}
}
看出来了吧,Integer类有一个默认在-128~127之间的常量缓存池,当我们的基本类型的数在这个之间的时候会指向缓存中的对象,也就是同一个对象,这就解释case 1的情况为什么会返回true。
case 2:
原理在case 1中已经分析,不在重复
case 3:
可能有朋友对第三种情况比较的困惑,不是说在-128~127之间是在缓存池里面取出数据吗,那么会什么会返回false呢?别急我们来看一下Integer的构造函数:
public Integer(int value) {
this.value = value;
}
我们可以看到Integer的构造函数之间创建一个对象,并没有从常量池中取出对象,显然两个不同的对象,地址之间的比较自然而然也就不相等了。
case 4:
这个比较容易理解自动装箱的值已经超过127,会创建两个不同的Integer对象,返回false。
总结
我们在比较Integer对象的时候最好避免使用==号之间的比较,建议用equals方法进行Integer对象的比较。