StringBuffer.equals()比较的是对象
- 同一对象不同内容,怎么比较都是true
- 不同对象相同内容,怎么比较都是false
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer aBuffer = new StringBuffer();
aBuffer.append("12");
StringBuffer bBuffer = new StringBuffer();
bBuffer.append("12");
System.out.println("相同对象不同内容:"+aBuffer.equals(aBuffer.reverse()));
System.out.println("不同对象相同内容:"+aBuffer.equals(bBuffer));
}
}
相同对象不同内容,结果为true
不同对象相同内容,结果为false
源码比较:
StringBuffer中
public boolean equals(Object obj) {
return (this == obj);
}
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;
}