81,094
社区成员
发帖
与我相关
我的任务
分享
/**
* 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 = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
此外还需要注意要常量池的问题,比如如下代码:
public class StringTests {
public static void main(String[] args) {
String a = "abc";
String b = new String("abc");
String c = new String("abc").intern();
System.out.println(a == b);
System.out.println(a == c);
}
}
输出是false,true,可以仔细研究下为什么。!sPassword.equal(sRepassword)
sPassword!=sRepassword是判断的两个变量的内存地址