What is an efficient way to compare StringBuilder objects

后端 未结 4 1074
无人共我
无人共我 2021-01-03 19:25

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());

bu

4条回答
  •  旧时难觅i
    2021-01-03 20:03

    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.

提交回复
热议问题