今天使用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; }