# 7.3对象的特殊函数

类的特殊函数

* 构造函数
* equals
* hashCode
* toString

java&#x4E2D;**==**&#x6BD4;较两个对象是否为**同一个对象**，

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

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

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

```java
    /**
     * 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)的必要条件，而非充分条件


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://moluo.gitbook.io/notes/bian-cheng-xue-xi/java/java-ji-chu/7.3-dui-xiang-de-te-shu-han-shu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
