Integer a = 127;
Integer a1 = new Integer(127);
Integer a2 = Integer.valueOf(127);
Integer b = 127;
Integer b2 = Integer.valueOf(127);
Integer c = 128;
Integer c1 = Integer.valueOf(128);
Integer d = 128;
Integer d1 = Integer.valueOf(128);
System.out.println(a == a1);
System.out.println( a2 == b2);
System.out.println(c == c1);
System.out.println( c1 == d1);
System.out.println(a == b);
System.out.println(c == d);
Integer a1 = new Integer(127);
Integer a2 = Integer.valueOf(127);
Integer b = 127;
Integer b2 = Integer.valueOf(127);
Integer c = 128;
Integer c1 = Integer.valueOf(128);
Integer d = 128;
Integer d1 = Integer.valueOf(128);
System.out.println(a == a1);
System.out.println( a2 == b2);
System.out.println(c == c1);
System.out.println( c1 == d1);
System.out.println(a == b);
System.out.println(c == d);
是这样的吗?
false
true
false
false
true
false
true
false
false
true
false
从结果可以看出JDK5的自动装箱实际上是调用了valueOf方法;
而Integer的valueOf方法源代码是这样的:
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
而IntegerCache中的缓存是这样的:
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
所以上面的结果咋看起来会让人不解。。。