Skip to content

Compare two StringBuilder objects (or StringBuffer) – equals

Compare StringBuilder example shows how to compare two StringBuilder objects in Java. Since the StringBuilder is a drop-in replacement for StringBuffer, this applies to compare two StringBuffer objects as well.

How to compare two StringBuilder objects in Java?

The StringBuilder (or StringBuffer) class has not implemented the equals method, it inherits the version defined in the Object class. The equals method of the Object class compares the object references, not the content.

So if you want to compare two StringBuilder object contents, comparing them with each other using the equals method does not work as shown in the below code example.

Output

As you can see in the above example, even though the contents of both of the StringBuilder objects are the same, the equals method returned false. The reason is, they both refer to different objects.

How to compare StringBuilder objects using the content?

We can convert the StringBuilder object to String and then use the equals method of the String class to compare the content as given below.

Output

This approach needs an additional step of converting StringBuilder to String which may not be efficient in terms of performance in some cases. Here is the source code of the toString method of the StringBuilder class.

As you can see, it creates a new String object using the internal character buffer array and returns it.

What is the preferred way to compare?

I would first check if both StringBuilder object has the same length i.e. the same number of characters. It will be a quick operation and will save us from comparing the objects if the length is not the same.

If they do have the same number of characters, I would compare each character of one StringBuilder object to another StringBuilder object as given below.

Output

I did not perform any benchmarking but I think this method should perform better than using the toString method to compare the StringBuilder or StringBuffer objects, especially in the cases where you want to compare lots of StringBuilder objects having content of different lengths.

This example is a part of the Java StringBuffer tutorial and Java StringBuilder tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.