int是java中的基本类型,Integer是java中的类,是int的包装类型
public class IntegerTest {
public static void main(String[] args) {
Integer a1 = 1;
Integer a2 = 1;
Integer e1 = 150;
Integer e2 = 150;
Integer b1 = new Integer(150);
Integer b2 = new Integer(150);
Integer c1 = new Integer(110);
Integer c2 = new Integer(110);
Integer d1 = Integer.valueOf(110);
Integer d2 = Integer.valueOf(110);
System.out.println("a1 == a2??"+(a1 == a2));
System.out.println("e1 == e2??"+(e1 == e2));
System.out.println("b1 == b2??"+(b1 == b2));
System.out.println("c1 == c2??"+(c1 == c2));
System.out.println("d1 == d2??"+(d1 == d2));
}
}
答案:
a1 == a2??true
e1 == e2??false
b1 == b2??false
c1 == c2??false
d1 == d2??true
结果分析:
我们发现1.2.5组调用了Integer.valueOf()
,JDK1.5开始有自动装箱、自动拆箱的功能,我们才可以Integer a1 = 1
来初始化一个Integer对象,否则就只能Integer b1 = new Integer(150);
来初始化一个Integer对象,这样更加方便。意思就是JDK提供的自动装箱,其实是由JVM去调用Integer.valueOf()
。
我们来看看Integer.valueOf()
源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这里调用了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;
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;
}
这段代码利用缓存思想,将 -128~127之间的数先缓存。因此1、2、5的答案分别为true、false、true。
而3、4由于是new新建对象,是在java堆中,==
是比较地址的,因此不管初始化值是多少,答案都是false。
再来看看:
int x = 110;
Integer c2 = new Integer(110);
System.out.println("c == x??"+(x == c));
答案是true,通过字节码发现调用了Integer.intValue()
先取出Integer的value,再进行比较。