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?
As you apparently already know,
StringBuilderinheritsequals()fromjava.lang.Object, and as suchStringBuilder.equals()returns true only when passed the same object as an argument. It does not compare the contents of twoStringBuilders!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 ofcharAt(i)for each character.