public class Test{
public static void main(String[] args){
test1();
}
public static void test1(){
Integer m=127;
Integer n=127;
System.out.println(m==n);
System.out.println(m.equals(n));
}
public static void test2(){
Integer m=127;
int n=127;
System.out.println(m==n);
}
public static void test3(){
Integer m=127;
Integer n=new Integer(127);
System.out.println(m==n);
System.out.println(m.equals(n));
}
public static void test4(){
Integer m=127;
Integer n=Integer.valueOf(127);
System.out.println(m==n);
System.out.println(m.equals(n));
}
public static void test5(){
Integer m=128;
Integer n=128;
System.out.println(m==n);
System.out.println(m.equals(n));
}
public static void test6(){
Integer m=128;
int n=128;
System.out.println(m==n);
}
public static void test7(){
Integer m=128;
Integer n=new Integer(128);
System.out.println(m==n);
System.out.println(m.equals(n));
}
public static void test8(){
Integer m=128;
Integer n=Integer.valueOf(128);
System.out.println(m==n);
System.out.println(m.equals(n));
}
}
一一运行上述test1()一直到test8()方法,你的结果能完全对么?
我根据昨天一笔试题然后总结到这里的。
有若干个知识点:
1)int 跟Integer、Integer.valueOf()、new Integer()做==比较时,只比较两者的数值,数值相等即为true.
根据这个原则,test2()和test6()都是输出为true;
2)When boxing (transforming int
to Integer
) the compiler uses a cache for small values (-128 - 127) and reuses the same objects for the same values.在-128-127之间时,包括边界值,Integer m=127,Integer n=Integer.valueOf(127),都会将127装箱成Integer类型,并且m和n共用同一个127的Integer类型。
根据这个原则,test1()输出为true,true;
3)当值不在-128-127之内时,Integer m=128,Integer n= 128或者Integer n=Integer.valueOf(128),也会将128装箱成Integer类型,但这时不再重用同一个Integer对象,而是各自一个了。此时的Integer m=128或Integer m=Integer.valueOf(128),都相当于new了一个Integer对象。
根据这个原则,test5()输出为false,true
4)当一个int数值用new创建时,无论在不在-128-127之间,都会创建一个Integer对象,而且不会重用
根据这个原则,test3()、test7()都输出为false,true
5)Integer m=数值和Integer m=Integer.valueOf(数值)的效果一样的,两者可以互换。他们在-128-127之内时,会重用Integer,在之外,不会重用。
根据这个原则,test4()输出为true,true;test8()输出为false,true
综上所述,int 跟包装类做==比较时,只比较数值大小,数值大小相等即为true;Integer m=数值的效果等同于Integer m=Integer.valueOf(数值),数值在-128-127之间时,装箱后的Integer对象会重用;超过此范围,装箱后的Integer对象不会重用;new Integer(数值),总会new一个对象,而且不是new缓存中的对象。==比较时,数值大小相等也会false。