7.3对象的特殊函数

类的特殊函数

  • 构造函数

  • equals

  • hashCode

  • toString

java中==比较两个对象是否为同一个对象

而equals()则可以由程序员自定义,只需要重写Object的equals()方法即可。未重写默认使用Object类的equals()方法,Object的equals()方法比较两个对象是否为同一个对象,源码如下:

public class Object {
    ...
    public boolean equals(Object obj) {
        return (this == obj);
    }
    ...
}

String类中自定义了equals()方法,String类中的equals()比较两个对象的值是否相等。源码如下:

    /**
     * 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;
    }

通常我们可以使用IDE快捷键为我们自动生成equals()方法

注意:有2个对象a和b,若a.equals(b),则a.hashCode()==b.hashCode();但a.hash()==b.hash(),不一定能推导出a.equals(b)。即a.hashCode()==b.hashCode()为a.equals(b)的必要条件,而非充分条件

Last updated

Was this helpful?