Java之equals理解

今天面试的时候,被面试官问到了 ’ == ’ 和 ’ equals ’ 的区别,最后他还总结 equals 是同通过比较 hashCode() 。其实我当时心里挺疑惑的,我记得好像不是比较 hashCode 的。

于是我看了下 String#equals 源码

String.class

/**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

发现比较的顺序

  1. 比较两个对象的地址是否相同
  2. 比较两个对象的类型
  3. 比较两个对象的值是否相同
  4. 详细比较两个对象的每个字符

如有不对,请指教!

发布了18 篇原创文章 · 获赞 0 · 访问量 423

猜你喜欢

转载自blog.csdn.net/mikelv01/article/details/104919573