public class Test2{
    public static void main(String[] args){
        int a = 1000;
        int b = 1000;
        Integer wa = a;
        Integer wb = b;
        System.out.println(wa.equals(wb));
        System.out.println(wa==wb);
    }
}

上面程序输出:true false

两个对象之间用等号五号比较,需要用equals进行比较,但是

public class Test2{
    public static void main(String[] args){
        int a = 1;
        int b = 1;
        Integer wa = a;
        Integer wb = b;
        System.out.println(wa.equals(wb));
        //对象用等号比较输出true
        System.out.println(wa==wb);
    }
}

上面程序输出:true true 

对象之间是无法用“==”号进行比较的?为什么输出true呢?

  Integer 的源码中,对传入参数i做了一个if判断。在-128<=i<=127的时候是直接用的int原始数据类型,而超出了这个范围则是new了一个对象。我们知道 == 符号在比较对象的时候是比较的内存地址,而对于原始数据类型是直接比对的数据值。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2021-04-02
  • 2021-07-15
  • 2022-12-23
  • 2021-08-21
  • 2021-05-02
猜你喜欢
  • 2022-12-23
  • 2021-09-21
  • 2022-01-18
  • 2022-12-23
  • 2021-11-02
  • 2022-12-23
相关资源
相似解决方案