源码阅读—String equals()

本文深入解析 Java 中 String 类的核心实现,包括构造、比较、哈希码等关键特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 类声明:

public final class String

    implements java.io.Serializable, Comparable<String>, CharSequence {

————————————————————————————————————————————————————————————————————————————————————————————————

/** The value is used for character storage. */

    private final char value[];

 /** Cache the hash code for the string */

    private int hash; // Default to 0

 /**

     * Initializes a newly created {@code String} object so that it represents

     * an empty character sequence.  Note that use of this constructor is

     * unnecessary since Strings are immutable.

     */

    public String() {

        this.value = new char[0];

    }


    /**

     * Initializes a newly created {@code String} object so that it represents

     * the same sequence of characters as the argument; in other words, the

     * newly created string is a copy of the argument string. Unless an

     * explicit copy of {@code original} is needed, use of this constructor is

     * unnecessary since Strings are immutable.

     *

     * @param  original

     *         A {@code String}

     */

    public String(String original) {

        this.value = original.value;

        this.hash = original.hash;

    }


/**

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

    }

<think>好的,用户想查看Java中equals方法的源码实现。首先,我需要回忆一下Java中Objectequals方法默认实现。Objectequals方法默认是比较对象引用是否相同,也就是和"=="操作符一样。但很多,比如String、Integer等都会重写这个方法,提供内容比较的功能。 接下来,我需要确认用户提到的具体是哪个equals方法,但问题中没有明确说明,所以可能需要先介绍Object的默认实现,然后以常用的String为例详细说明。根据用户提供的引用资料,特别是引用[3]和[4],他们可能对Stringequals方法更感兴趣。 然后,我需要按照用户的要求,将源码实现分步骤解释清楚。需要确保使用正确的格式,行内公式用$...$,独立公式用$$...$$,但在这个问题中可能不太涉及数学公式,更多是代码和文字描述。同时,要使用中文回答,结构清晰,并生成相关问题。 需要注意的是,用户提供的引用中有关于StringBuilder和Stringequals比较的例子,这可能涉及到不同型对象的比较,这在源码中是如何处理的。例如,Stringequals方法会先检查型是否匹配,再比较内容,而StringBuilder没有重写equals方法,所以使用的是Object的实现,即比较引用。 接下来,我需要组织回答的结构,首先介绍Objectequals方法,然后以String为例详细解读源码,说明每一步的作用,比如型检查、字符逐个比较等。同时,要引用用户提供的参考资料,比如引用[3]中的源码解读部分,确保引用标识正确添加。 最后,生成相关问题时,要考虑用户可能的后续疑问,比如equals==的区别,如何正确重写equals方法,以及不同之间比较时的注意事项等。确保问题覆盖用户可能感兴趣的方向,帮助他们深入理解equals方法的实现和使用。</think>### Java `equals` 方法源码实现解析 #### 1. **`Object` 的默认实现** `equals` 方法定义在 `java.lang.Object` 中,默认行为是**比较对象的引用是否指向同一内存地址**(即与 `==` 运算符等价): ```java public boolean equals(Object obj) { return (this == obj); } ``` - 如果未重写此方法,任何的实例比较时均基于引用而非内容[^1][^2]。 #### 2. **`String` 的重写实现** `String` 重写了 `equals` 方法以实现**内容比较**。源码如下[^3][^4]: ```java public boolean equals(Object anObject) { if (this == anObject) { // 1. 检查是否为同一对象 return true; } if (anObject instanceof String) { // 2. 检查型是否为String String anotherString = (String) anObject; int n = value.length; if (n == anotherString.value.length) { // 3. 检查长度是否一致 char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { // 4. 逐个字符比较 if (v1[i] != v2[i]) return false; i++; } return true; } } return false; } ``` #### 关键步骤解读: 1. **引用检查**:若对象相同,直接返回 `true`。 2. **型检查**:通过 `instanceof` 确保比较对象是 `String` 型。 3. **长度比对**:若长度不同,直接返回 `false`。 4. **逐字符比较**:循环遍历字符数组,完全一致才返回 `true`。 #### 3. **不同型对象的比较示例** 用户提供的案例: ```java String str = "abc"; StringBuilder sb = new StringBuilder("abc"); System.out.println(str.equals(sb)); // false(型不同) System.out.println(sb.equals(str)); // false(StringBuilder未重写equals) ``` - `StringBuilder` 未重写 `equals`,因此调用 `Object` 的默认实现,仅比较引用[^1][^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值