Home>

I'm studying Java.
There is a difference between identity and equivalence when comparing objects.

public class CompareStringBuilder {
    public static void main (String [] args) {
        var builder1 = new StringBuilder ("Ai");
        var builder2 = new StringBuilder ("Ai");
        System.out.println (builder1 == builder2);// 1
        System.out.println (builder1.equals (builder2));// 2

    }
}


1 above is false because we are comparing different identities.
I thought that 2 would be true because I was comparing equivalence, but both 1 and 2 were false.

Why?

By the way, it is the content of the text "Self-study Java" p92-93.
Since there is no notation of the sample code of equals, I thought that it was written incorrectly, so I posted it.

  • Answer # 1

    It is a correct recognition to compare using the equals method to determine "equivalent (equivalent)".
    However, there is one pitfall.

    The default definition of the equals method of the Object class is a specification that confirms identity.
    in this case,

    var builder1 = new StringBuilder ("Ai");
    var builder2 = new StringBuilder ("Ai");


    Since each Object is NEW as shown, the Object is different and there is no identity, so false is returned at this point.
    If you want to determine the equivalence of your own object class, you need to override the equals method in that class.
    Please refer to the following URL for the detailed method.
    https://pointsandlines.jp/server-side/java/equals

  • Answer # 2

    It ’s a little annoying, but
    We are comparing that the equals methods of all superclasses, Object, are also inherently identical.

    However, the frequently used String equals are
    It is a process that overrides the method of Object and compares that they are equivalent.
    It's easy to misunderstand this because it is mentioned in most commentary books and sites.
    Actually, this is a special one.

    StringBuilder's equals doesn't specifically override Object's, so
    It is compared to be the same.

  • Answer # 3

    I thought that 2 would be true because it compares equivalence.

    Yes,StringBuilderTo compare each other, just "whether they are the same instance" without looking at the contents at all.


    StringBuilderIs essentially a class that isn't supposed to be routed around and used around, as thread safety isn't guaranteed either.