直接看重点吧:
使用 equals 时,会判断其是否是String 类型,如果不是,则直接返回false
附上源码:
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;
}
所以,下列题目中
若有下列定义,下列哪个表达式返回false?
String s = "hello";
String t = "hello";
char c[] = {'h','e','l','l','o'} ;
A: s.equals(t);
B: t.equals(c);
C: s==t;
D: t.equals(new String("hello"));
正确答案选择:B