先看一个代码段:
public class csdn_Integer {
public static void main(String[] args) {
int a = 11;
int b = 11;
Integer c = 11;
Integer d = 11;
Integer e = new Integer(11);
Integer f = 555;
Integer g = 555;
System.out.printf("a==b:%b\na==c:%b\nc==d:%b\nc==e:%b\ne==f:%b\n",a==b,a==c,c==d,c==e,f==g);
}
}
结果 :
a==b:true
a==c:true
c==d:true
c==e:false
e==f:false
Process finished with exit code 0
分析:
1.与String类似,Integer也有常量池,通过Integer = x;定义的变量会先在常量池查找(且Integer和int共享常量池),如果存在就引用,没有就在常量池新建;new Integer(x);则不查找常量池,直接在堆中新建。
注意:这里Integer使用常量池的数据范围是-128 ~~ 127。超过这个范围的数据不引用常量,全部新建。
/** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as required by JLS. * * The cache is initialized on first usage. The size of the cache * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. * During VM initialization, java.lang.Integer.IntegerCache.high property * may be set and saved in the private system properties in the * jdk.internal.misc.VM class. */
2.对于f与g,因为555 > 127所以无论怎么声明都是新建。