任何人都知道Java中的String.equals()
中使用的算法是什么? Java如何比较两个单词?
答案 0 :(得分:5)
来自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;
}
答案 1 :(得分:2)
您可以在JDK中看到所有java类的实现。
只需转到JDK_HOME,找到' src.zip ',其中包含所有可以轻松找到String类实现的java类的源代码。