##一,我们先来看个例子
package com.wz.test;
public class TestInteger {
public static void main(String[] args) {
Integer a = 1000;
Integer b = 1000;
Integer c = new Integer(1000);
Integer d = new Integer(1000);
Integer e = 100;
Integer f = 100;
int g = 1000;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(e == f);
System.out.println(a == g);
}
}
答案是:false false true true;你答对了吗?大神请忽略。
楼主之前对此类问题也是模棱两可,决定问题不能搁着,索性去看下jdk源码,对Integer的定义。
那么在此之前呢,我们需要明确,‘==’两边如果是对象,则比较的是引用地址;如果是常量,则比较的是其值。
##二,知其然知其所以然
上面提到的a-f都是对象,但是又有所区别。a,b是将基本数据类型自动装箱成Integer对象,而装箱使用到的函数正是Integer的valueOf(int i)方法,那么我们就有疑问了,e,f不也是自动装箱了吗?为什么得到的结果却不一样。带着问题我们去看下源码,这里我读的是jdk7。
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
我们看到这里有IntegerCache,先不说再点开IntegerCache看看。
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];//这里提供了一个Integer类型的数组用来缓存-127~128的int数
static {
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
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);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
看完源码,我们知道,当要被装箱的int数在-127~128之间的时候,会直接从IntegerCache类中cache数组去读,这和String在创建时类似,这个稍后再总结。我们再来看看cache的定义,Integer.MAX_VALUE的值为2147483647(MIN_VALUE=-2147483648),这几句其实就是判断给的值如果大于127,再和Integer.MAX_VALUE比较,取最小值赋给high(丢失精度就是这么来的)。然后会根据结果创建出cache数组,其他的没什么了。
到这里,我们就知道a,b为什么是false,而e,f是true了。c,d因为都是new出来的,内存地址不同,这个就不多说了。最后看下a和g的比较,这里为什么又变成true了呢?原来,当包装类型和基本类型比较时,包装类型会自动拆箱变成基本类型,然后再进行‘==’比较,这时比较的是值,当然一样啦~~
例子虽小,简单总结下:
1)两个包装类型比较,先看数值在不在-127~128之间,如果在,就从Integer的缓存数组中去取,此时值一样则为true;不在其区间的,都是false!
2)new 出来的对象比较都为false;
3)包装类型和基本类型比较,包装类型先拆箱,在比较。
第一次写博客,如有不对之处,还请见谅,欢迎指正交流~~