Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an efficient way to compare StringBuilder objects

Well I have two StringBuilder objects, I need to compare them in Java. One way I know I can do is

sb1.toString().equals(sb2.toString()); 

but that means I am creating two String objects, is there any better way to compare StringBuilder objects. Probably something where you do not need to create additional objects?

like image 989
user1344389 Avatar asked Jun 13 '12 02:06

user1344389


People also ask

How is StringBuilder more efficient?

Creating and initializing a new object is more expensive than appending a character to an buffer, so that is why string builder is faster, as a general rule, than string concatenation.

How do you check for equality in StringBuilder?

The Equals method uses ordinal comparison to determine whether the strings are equal. . NET Core 3.0 and later versions: The current instance and sb are equal if the strings assigned to both StringBuilder objects are the same. To determine equality, the Equals method uses ordinal comparison.

What are the 3 ways to compare two String objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.

How do you know if two String builders are equal?

Syntax: public bool Equals (System. Text. StringBuilder sb); Here, sb is an object to compare with this instance, or null. Return Value: It will return true if this instance and sb have an equal string, Capacity, and MaxCapacity values; otherwise, false.


2 Answers

As you apparently already know, StringBuilder inherits equals() from java.lang.Object, and as such StringBuilder.equals() returns true only when passed the same object as an argument. It does not compare the contents of two StringBuilders!

If you look at the source, you'll conclude that the most efficient comparison (that didn't involve creating any new objects) would be to compare .length() return values, and then if they're the same, compare the return values of charAt(i) for each character.

like image 134
Ernest Friedman-Hill Avatar answered Sep 30 '22 18:09

Ernest Friedman-Hill


Since Java 11, StringBuilder implements Comparable, so you can use a compareTo method for the equality test:

System.out.println(sb1.compareTo(sb2) == 0); 
like image 27
ZhekaKozlov Avatar answered Sep 30 '22 19:09

ZhekaKozlov