Home>

Thank you very much for seeing it.
Below are the questions.

Question

If "A" reference is stored in both String type and StringBuilder type and it is compared with "A" by equals, only StringBuilder type returns false.
Equals were predicted to be true because equals recognizes that it "sees if they are equal."

Since "A" of "xxx.equals("A")" is judged as String type, does it mean that "str" ​​of String type and "sb" of StringBuilder type do not match? ?
Also, how do you perform equivalence judgment with "sb"?

Code examples and results
public class Sample{
    public static void main(String[] args) {
        String str = new String("A");
        StringBuilder sb = new StringBuilder("A");
        // String and "A"
        if(str.equals("A")) {
            System.out.println(true);
        }
        else {
            System.out.println(false);
        }
        // StringBuilder and "A"
        if(sb.equals("A")) {
            System.out.println(true);
        }
        else {
            System.out.println(false);
        }
    }
}
result
true
false
  • Answer # 1

    The conditions for equals to be true are specified in the documentation for each class.

    String#equals

    The result is true only if the argument is not null and is a String object representing the same character sequence as this object.

    The equals method of StringBuilder is not overridden and is only listed by name as "Method inherited from class java.lang.Object". In this case, since the definition has not changed from the inheritance source, it will be true only if it is the same as Object#equals, that is, if the arguments are the same object.

    If you want to compare the contents, StringBuilder implements CharSequence, so you can use String#contentEquals.

  • Answer # 2

    I think it's just a mismatch because String and StringBuilder have different types.

  • Answer # 3

    The recognition that equals "sees if they are equal"

    Normally, we do not consider values ​​of different types to be equivalent.

  • Answer # 4

    Normally, the equals method tests if objects are equal.
    Is the referenced object the same?

    On the other hand, equals of String class is overridden,
    Even if the objects are different, if the character strings are the same, it is judged as the same value.

    Also, how do you perform equivalence judgment with "sb"?

    Let's compare the strings.

    sb.toString().equals("A")

  • Answer # 5

    In the first place, it has already been pointed out that it will be false because the type is different.
    Since StringBuilder does not override Object#equals, it seems to be true only when the same reference is made.

    StringBuilder sb1 = new StringBuilder("a");
    StringBuilder sb2 = new StringBuilder("a");
    StringBuilder sb3 = sb1;
    System.out.println(sb1.equals(sb2));// false
    System.out.println(sb1.equals(sb3));// true