两个Integer直接判断相等

知道Integer属于对象类型的,因此在比较的时候直接使用 Integer实体.equals() 来进行比较。能够忽然发如今数字小的时候直接使用== 也能够判断是正确的。后来搜索发现原来缘由是这样:web

先看段代码:orm

  1. public static void main(String[] arg){对象

  2.         Integer a=300000;内存

  3.         Integer b=300000;it

  4.         Integer c=30;搜索

  5.         Integer d=30;webkit

  6.         System.out.println(a.equals(b));数据

  7.         System.out.println(a==b);   //falsestatic

  8.         System.out.println(a==300000);数字

  9.         System.out.println(d.equals(c));

  10.         System.out.println(d==c);

  11.         System.out.println(d==30);

  12.  }

打印结果说明-128 到 127的数值,怎么比较都同样,其它的只有equals时才相等.

Java自动装箱是对于从 -128 到 127 之间的信息值,它们在被装箱为对象数据后会在内存中被重用,也就是对于相同的值,返回的是同一个对象.直接与数值比较时,大概是拆箱比较了,就跟 int的比较同样了,因此仍是相等的.

相关文章
相关标签/搜索