What is an efficient way to compare StringBuilder objects

java, stringbuilder

Solution

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.

Problem

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?

Original source