日期:2014-05-20 浏览次数:20981 次
public class StringMethod {
public static void main(String [] args) {
String s1 = "hello world";
StringBuffer s2 = new StringBuffer("hello world");
System.out.println(s1.equals(s2));
}// [color=#FF0000]为什么返回 false??? [/color]
}
public boolean equals(Object anObject) {
if (this == anObject) {//直接比较引用是否相同,相同返回true
return true;
}
if (anObject instanceof String) {//看传入类型是否是String,是的话比较String的内容,就是先看两个String类型的长度是否相同,不同跳出返回false,相同再比较组成String的char[]每个是否相同一样返回true
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;
}