读书人

请问为什么StringBuffer比较后输出Not

发布时间: 2011-12-21 23:56:01 作者: rapoo

请教为什么StringBuffer比较后输出Not Equal
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

读书人网 >J2SE开发

热点推荐