这题的主要考点是 String的equals方法。
/**
* 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、指向是同一个String对象为 true。
2、被比较的对象类型不是String为 false。
3、2者都是String类型,但是长度不同为 false。
4、2者都是String类型,值一样为 true(String是对char数组的封装,就是判断2个char数组相同下标的值是否完全一样)
所以s、t、c使用equals是俩俩相同的。==的判断可以看做是否指向同一个对象。显然t和c指向不同对象。注意:这里的s和t其实指向的是同一个对象。String有个常量池。