equals方法,超类Object中有这个equals()方法
public boolean equals(Object obj) {
return (this == obj);
}
a.equals(b),a和b引用的是同一个对象时,则返回true,否则返回false。
String,Date等重写了这个方法。
在String类中重写的equals方法
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;
}
String s1 = new String("aa");
String s2 = new String("aa");
System.out.println("s1 == s2:"+(s1 == s2));//false
System.out.println("s1.equals(s2):"+s1.equals(s2));//true
s1 == s2,比较s1和s2两个字符串对象的引用。
s1.equals(s2),重写后,只要字符串对象不为空且与当前字符串对象的内容一样,就返回true。