views:

344

answers:

3

Possible Duplicate:
Comparing StringBuffer content with equals

StringBuffer s1= new StringBuffer("Test");
StringBuffer s2 = new StringBuffer("Test");
if(s1.equals(s2)) {
  System.out.println("True");
} else {
  System.out.println("False");
}

Why does that code print "False"?

+3  A: 

StringBuffer equals isn't overridden to check content. It's using the default "shallow equals" that compares references it inherits from java.lang.Object.

duffymo
its overloaded or overrided?????
rocker
overrided or overrode?
runrunraygun
overrode or overridden?
Michael Krauklis
overridden or over... nope, i'm out :)
runrunraygun
A: 

you are asking if the two buffers are the same object, which they are not. You need to be checking if the contents is the same, off the top of my head you could do this.

if(s1.ToString() = s2.ToString())
{ System.out.println("True"); } else System.out.println("False");
runrunraygun
You're answering the C# question, but the question is about Java. They are similar but the example code is different ;-)
Joachim Sauer
yeah I know. I answered before the question was tagged properly.
runrunraygun
+5  A: 

StringBuffer does not override the Object.equals method, so it is not performing a string comparison. Instead it is performing a direct object comparison. Your conditional may as well be if(s1==s2). If you want to compare the strings you'll need to turn the buffers into strings first.

See http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html

Edit: I'm assuming we're in a java world.

p.s. If you're in a single-threaded environment, or your buffers are isolated to a single thread, you should really be using a StringBuilder instead of a StringBuffer.

Michael Krauklis
thanks Michaelits really help me.....
rocker