【问题标题】:Java String.equals() algorithm [closed]Java String.equals() 算法 [关闭]
【发布时间】:2012-12-18 06:05:11
【问题描述】:

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

【问题讨论】:

标签: java string algorithm


【解决方案1】:

来自String的简单函数

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

【讨论】:

  • 所以Java只是用它来比较两个字符串?没有使用任何算法?
  • 嗯...您现在正在查看算法,@Dummy1234。
  • 那么,这个算法叫什么名字?
  • @Dummy1234,如果算法没有名字,不要过度打扰。
  • @Dummy1234 为方便起见,您可以将其命名为 Dummys Algorithm ;-}
【解决方案2】:

你可以看到JDK中java类的所有实现。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 2010-09-08
    • 2012-11-30
    • 2021-04-23
    相关资源
    最近更新 更多