JDK 8 equals() & ==

equals() 是 java.lang.Object 的一个实例方法,被所有的子类所继承(可被复写)。

以下是 JDK 8 中 java.lang.Object.equals() 源码:

1 public boolean equals(Object obj) {
2         return (this == obj);
3     }

这个方法很简单,当自身和自身比较时,才返回 true。

 

不同的子类可能会重写这个方法,提供不同的实现。

下面是 JDK 8 java.lang.String.equals(Object anObject) 源码:

 1 /**
 2      * Compares this string to the specified object.  The result is {@code
 3      * true} if and only if the argument is not {@code null} and is a {@code
 4      * String} object that represents the same sequence of characters as this
 5      * object.
 6      *
 7      * @param  anObject
 8      *         The object to compare this {@code String} against
 9      *
10      * @return  {@code true} if the given object represents a {@code String}
11      *          equivalent to this string, {@code false} otherwise
12      *
13      * @see  #compareTo(String)
14      * @see  #equalsIgnoreCase(String)
15      */
16     public boolean equals(Object anObject) {
17      if (this == anObject) {
18          return true ;
19      }
20      if (anObject instanceof String) {
21          String anotherString = (String)anObject;
22          int n = count ;
23          if (n == anotherString.count ) {
24            char v1[] = value ;
25            char v2[] = anotherString.value ;
26            int i = offset ;
27            int j = anotherString.offset ;
28            while (n-- != 0) {
29               if (v1[i++] != v2[j++])
30                return false ;
31           }
32            return true ;
33          }
34      }
35      return false;
36     }

从上面可以看到这个方法返回 true 的情况:

  1. 自己与自己比较;
  2. 两个对象都是String,且内容相同。

 

需要注意的:

1、equals()

实例方法,可以被子类重写;

必须满足自反性、对称性、传递性、一致性、not-null 和 null 永远不相等。

2、==

运算符,对于对象而言,判断引用是否相等,对于 primitive type 而言,判断值是否相等;

Java 不支持开发者重载运算符,但是 Java 自己重载了一些运算符(最常见的就是 +,+ 可以应用于数值、字符、字符串)。

3、equals() 和 hashCode() 关系密切

java.lang.Objecct.hashCode() 的实现比较简单,将对象在内存中的地址转换成一个整数,返回这个整数。

一般而言,如果 equals() 重写的话,hashCode() 也需要重写:要保证 equals() 返回 true 时,hashCode() 应该返回相同的值;equals() 返回 false 时,hashCode() 可能返回相同的值(JLS 对这种情形没有做规定,java.lang.String 就出现了这样的情况,即哈希碰撞),但最好还是返回不同的值。

4、java.lang.String.equals() 没有使用 hashCode()

java.lang.String 存在特例,不同的字符串具有相同的 hashCode (哈希碰撞),即 equals() 返回 false,但是 hashCode() 返回相同的值。

因此判断两个对象是否相等,最好使用 equals() 而非 hashCode() 进行判断。

可以阅读这篇文章

 

posted @ 2016-01-05 14:00  赫尔修斯  阅读(439)  评论(0编辑  收藏  举报