Difference between '==' and equals in Java

1. About " == "

The effect of == on basic types and reference types is different;

Basic type: the comparison is whether the values ​​are the same;

Reference type: the comparison is whether the references are the same;

Code example:


String x = "string";
String y = "string";
String z = new String("string");
System.out.println(x==y); // true
System.out.println(x==z); // false
System.out.println(x.equals(y)); // true
System.out.println(x.equals(z)); // true

 Explanation: Because x and y point to the same reference, == is also true, and the new String() method is rewritten to open up memory space, so the == result is false, and equals always compares values, so the result Both are true.

2. About equals

equals is essentially ==, but String and Integer rewrite the equals method and turn it into a value comparison. See the code below to understand.

First look at the default equals compares an object with the same value, the code is as follows:

class Cat {
    public Cat(String name) {
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Cat c1 = new Cat("王磊");
Cat c2 = new Cat("王磊");
System.out.println(c1.equals(c2)); // false

The output is beyond our expectation, it is false? What's going on, you can see the source code of equals, the source code is as follows:


public boolean equals(Object obj) {
    return (this == obj);
}

In this way, equals is essentially ==;

That's the question, why do two String objects with the same value return true? code show as below:


String s1 = new String("老王");
String s2 = new String("老王");
System.out.println(s1.equals(s2)); // true

Similarly, when we entered the equals method of String, we found the answer, the code is as follows:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

It turned out that String rewrote the equals method of Object and changed the reference comparison to value comparison.

3. Summary 

"==" is a value comparison for basic types, and a reference comparison for reference types; and equals is a reference comparison by default, but many classes re-equals methods, such as String, Integer, etc., turn it into Value comparison is performed, so in general, equals compares whether the values ​​are equal.

Guess you like

Origin blog.csdn.net/qq_43780761/article/details/127134312
Recommended