Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the StringBuffer equals method compare content? [duplicate]

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"?

like image 507
rocker Avatar asked Feb 03 '10 13:02

rocker


People also ask

Does StringBuffer have equals method?

The equals() method of the StringBuffer class But, unlike the Sting class the StringBuffer does not override the equals() method. Its functionality is same as in the Object class. Therefore, to get true you need to compare references pointing to the same value using the equal method.

How do I compare the contents of two StringBuffer objects?

StringBuffer's equals method returns true only when a StringBuffer object is compared with itself. It returns false when compared with any other StringBuffer, even if the two contain the same characters. Still if you want to check if the content is equal in these two StringBuffer Objects, you can use this: sb1.

Can we compare String with StringBuffer?

When an object of String is passed, the strings are compared. But when object of StringBuffer is passed references are compared because StringBuffer does not override equals method of Object class.

What is a StringBuffer method?

A string buffer is like a String , but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. String buffers are safe for use by multiple threads.


1 Answers

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.

like image 105
Michael Krauklis Avatar answered Oct 22 '22 13:10

Michael Krauklis