public class Test1
{
public static void main(String args[])
{
int a=5;
Integer a1=5,a2=5;
Integer a3=new Integer(5);
System.out.printf("a %s %s\n",a==a1,a==a3);
System.out.printf("a1 %s %s\n",a1==a2,a1==a3);
Integer a4=500,a5=500;
System.out.println(a4==a5);
System.out.println(a4.equals(a5));
}
}
==在比较两个Integer值,当数值在IntegerCache.low和IntegerCache.high之间,即[-128,127]之间的时候,会直接返回缓存中的值,当不在此范围之内,就是自动装箱,重新生成一个对象,所以,当两个值为128时,如果用==比较两个数的值,因为引用不一样,则返回false,所以应该用equals()方法来避免。