比较两个Integer的值是否相等

来源:互联网 发布:做长微博的软件 编辑:程序博客网 时间:2024/05/16 08:48

Integer比较大小的问题

遇到比较两个Integer值是否相等的问题,直接用”==”判断的,结果却是false.
下面看下例子:

public class Test {    public static void main(String[] args) {        Integer a = 10;        Integer b = 10;        System.out.println(a==b);        Integer c = 1000;        Integer d = 1000;        System.out.println(c==b);    }}

结果是:

truefalse

JVM会自动缓存-128~127范围内的值,所以所有在这个范围内的值相等的Integer对象都会共用一块内存,而不会开辟多个,所以用”==”判断为true;
超出这个范围内的值对应的Integer对象有多少个就开辟多少个内存,这样做是为了节省内存消耗。
所以我们最好用

a.equal(b)

或者

a.intValue()==b.intValue()