用String的equals方法比较一个StringBuffer的内容是否相等?
如下代码中str 与 buffer中的内容都是Java,为什么却输出Both are not equal.
String str = "Java ";
StringBuffer buffer = new StringBuffer(str);
if(str.equals(buffer)){
System.out.println( "Both are equal ");
}else{
System.out.println( "Both are not equal ");
}
------解决方案-------------------- 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 ,一个StringBuffer,你比个啥啊
str.equals(buffer.toString()) 肯定返回true