package lan;
public class Test {
public static void main(String[] args) {
Integer i1 = 4;
Integer i2 = 4;
System.out.println(i1 == i2);
}
}
当i1、i2的值在-128~127之间时,输出true,否则为false。
java language specification-3.0 写道
If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
在命令行通过JDK自带的反汇编工具javap对.class文件进行反汇编:javap -c Test
Compiled from "Test.java"
public class lan.Test extends java.lang.Object{
public lan.Test();
Code:
0: aload_0
1: invokespecial #8; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_4
1: invokestatic #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_1
5: iconst_4
6: invokestatic #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
9: astore_2
10: getstatic #22; //Field java/lang/System.out:Ljava/io/PrintStream;
13: aload_1
14: aload_2
15: if_acmpne 22
18: iconst_1
19: goto 23
22: iconst_0
23: invokevirtual #28; //Method java/io/PrintStream.println:(Z)V
26: return
}
可以看出Integer i = 4实际上就是 Integer i = Integer.valueOf(4);于是查看JDK源代码:
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);
}
private static class IntegerCache {
private 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);
}
}
从上面两段代码可以看出Integer i = x(x为-128~127之间的数),返回的是同一个对象的引用,只有超出这个范围才会重新创建一个Intger对象。因此也就解释了前面的现象。