What is an efficient way to compare StringBuilder objects

后端 未结 4 1049
无人共我
无人共我 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条回答
  •  一整个雨季
    2021-01-03 20:07

    Two StringBuilder objects are never equal. Use .toString() to get the string representation for both the objects and then use .equals() to compare the objects. This way equals() method from the String class gets invoked that compares the string value of the objects instead of comparing the memory location.

    StringBuilder a= new StringBuilder("HELLO JAVA");
    StringBuilder b= new StringBuilder("HELLO JAVA");
    if (a.toString().equals(b.toString())){
    System.out.println("Objects are equal");
    }
    

提交回复
热议问题