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?
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.
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.
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
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.
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 StringBuilder
s!
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.
Since Java 11, StringBuilder
implements Comparable
, so you can use a compareTo
method for the equality test:
System.out.println(sb1.compareTo(sb2) == 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With