Java中StringBuffer类的equals()方法
今天使用StringBuffer类的equals()方法进行内容比较时发现两个问题
- 同一对象不同内容,怎么比较都是true
- 不同对象相同内容,怎么比较都是false
如下:
package _3_5_test;
public class ThirtySevenTest {
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));
}
}

查看API后发现StringBuffer类中的equals()方法是继承自Object类的,没有进行重写,所以这个equals()方法是比较对象的。
查看源码后发现:
StringBuffer类的equals()方法是这样子的
public boolean equals(Object obj) { return (this == obj); }
而String类的equals()方法是这样的
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; }

浙公网安备 33010602011771号