class D
{
public static void main(String[] args)
{
String s1 = new String( "hello ");
String s2 = new String( "hello ");
if (s1.equals(s2))
System.out.println( "equal ");
else
System.out.println( "not equal ");
}
}
class E
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer( "hello ");
StringBuffer sb2 = new StringBuffer( "hello ");
if (sb1.equals(sb2))
System.out.println( "equal ");
else
System.out.println( "not equal ");
}
}
Class D输出equal,这个可以理解
但是Class E 为什么是not equal呢?StringBuffer的机制是怎么样的?
------解决方案--------------------
StringBuffer调用的是Object的equals()方法,它比较的是是否指向 同一个对象,和==一样。
for non-null reference values x and y,this method returns true,if and only if x and y refer to the same object