在劫

吾生也有涯,而知也无涯 。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
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了一个对象。我们知道 == 符号在比较对象的时候是比较的内存地址,而对于原始数据类型是直接比对的数据值。

posted on 2016-12-15 00:57  长嘴大耳怪  阅读(685)  评论(0编辑  收藏  举报