-5

有人知道String.equals()Java中使用的算法是什么吗?Java如何比较两个词?

4

2 回答 2

5

字符串中的简单函数

    /**
 * 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;
}
于 2012-12-18T06:08:46.183 回答
2

您可以在 JDK 中查看所有 java 类的实现。

只需转到您的 JDK_HOME,您可以在其中找到“src.zip ,其中包含所有 java 类的源代码,您可以在其中轻松找到 String 类的实现。

于 2012-12-18T07:20:31.870 回答