知道Integer属于对象类型的,因此在比较的时候直接使用 Integer实体.equals() 来进行比较。能够忽然发如今数字小的时候直接使用== 也能够判断是正确的。后来搜索发现原来缘由是这样:web
先看段代码:orm
public static void main(String[] arg){对象
Integer a=300000;内存
Integer b=300000;it
Integer c=30;搜索
Integer d=30;webkit
System.out.println(a.equals(b));数据
System.out.println(a==b); //falsestatic
System.out.println(a==300000);数字
System.out.println(d.equals(c));
System.out.println(d==c);
System.out.println(d==30);
}
打印结果说明-128 到 127的数值,怎么比较都同样,其它的只有equals时才相等.
Java自动装箱是对于从 -128 到 127 之间的信息值,它们在被装箱为对象数据后会在内存中被重用,也就是对于相同的值,返回的是同一个对象.直接与数值比较时,大概是拆箱比较了,就跟 int的比较同样了,因此仍是相等的.