java equals和==的区别

来源:互联网 发布:网络传销案 编辑:程序博客网 时间:2024/05/22 12:10

java equals和==的区别

也算是一直以来都没有搞清楚的问题,这次认真的看了下代码,搞定这个问题。
初学Java的时候总是喜欢用==来判断两个String是否相等,也闹了很多的错误。
当我们调用==时候,则会比较两个变量的值,如果是 基本类型则可以直接比较,如果是String则会比较他们在内存中的地址,举一个简单的例子

Student student1 = new Student();Student student2 = new Student();System.out.println(student1.equals(student2));System.out.println(student1 == student2);

上面的代码中 输出false false ,我们看一下类中equals的方法

 public boolean equals(Object o) {        return this == o;    }

直接返回的是==,也就是说类的equals的本质和==是一致的,比较的仅仅是他们在内存的地址,当 我们new了两个student后,将是不同的地址,所以就会是false。

那么大家也可能看过下面的例子

String a = new String("a");String b = new String("a");System.out.println(a == b);System.out.println(a.equals(b));

为什么输出就是false true ,我们在点击 equals方法进去看一下,会发现

 @Override public boolean equals(Object other) {        if (other == this) {          return true;        }        if (other instanceof String) {            String s = (String)other;            int count = this.count;            if (s.count != count) {                return false;            }            // TODO: we want to avoid many boundchecks in the loop below            // for long Strings until we have array equality intrinsic.            // Bad benchmarks just push .equals without first getting a            // hashCode hit (unlike real world use in a Hashtable). Filter            // out these long strings here. When we get the array equality            // intrinsic then remove this use of hashCode.            if (hashCode() != s.hashCode()) {                return false;            }            for (int i = 0; i < count; ++i) {                if (charAt(i) != s.charAt(i)) {                    return false;                }            }            return true;        } else {            return false;        }    }

可以看到他会在count和hashcode值相同时候,比较字符串的值是否相同,所以上面的答案就呼之欲出了。

原创粉丝点击