Integer数值小于127时使用==比较的坑

Java在处理Integer时使用了一个缓存,其中缓存了-128到127之间的数字对应的Integer对象,所以在绝大多数情况下,当我们把2个小于128的Integer对象用==比较时,Java往往是用缓存中的对象进行的比较,得到的结果也往往是true,比如这样:

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

输出的结果全是true

如果用debug模式就会发现,这几个对象的id都是一样的,因为他们都是从缓存中获取的同一个对象。

Integer f=new Integer(1);

人工new一个Integer对象,此时这个对象就不是从缓存中获取的了,此时再用==比较的话,返回的就是false,比如这样:

public class Test {
    public static void main(String[] args){
        Integer a=1;
        Integer e=new Integer("1");
        Integer f=new Integer(1);
        System.out.println(a==e);
        System.out.println(a==f);
 
    }
}

输出的都是false

 

结论:

1,尽量不要用new的形式来获得Integer对象。

2,Integer对象比较大小时,不要用==,尽量使用equals方法。

原文地址:https://www.cnblogs.com/uzxin/p/12205639.html