[Java basic knowledge] thoroughly understand the difference between == and equals

[Java Basics] What is the difference between == and equals?
There are two ways to test whether two variables are equal in a Java program, one is to use the == operator, and the other is to use the equals() method.
1. Interpretation of "=="
The effect of == for basic types and reference types is different, as shown below:
(1). Basic types: basic types are stored in the stack, and for basic types == The comparison is whether the values ​​are the same.
Eight basic types: byte, short, int, long, float, double, char, boolean

int i=8;
double x=8.00;
System.out.println(i==x); // true

(2). Reference type: For reference types == compares whether the addresses of two objects are the same, that is, whether they refer to the same object.

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

Code interpretation: For variables in the constant pool, because x and y point to the same reference, == is true, and the new String() method is overridden to open up memory space, so the result of == is false. d=========================================================================================================================================================================================================================:

2. "equals" interprets
the address used to compare objects, so its comparison of reference types has the same effect as ==. Equals is essentially ==, except that String and Integer have rewritten the equals method and changed it to Become a value comparison.

First, let’s look at the default case that 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 turned out to be false. What's the matter? Just read the equals source code, the source code is as follows:

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

It turns out that equals is essentially ==.

So the question is, 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));//3true

Similarly, we enter the equals method of String to find 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 turns out that String rewrites the equals method of Object, changing the comparison of references to comparison of values.

Summary: == is a value comparison for basic types, and a reference for reference types; and equals is a reference comparison by default, but many classes have renewed the equals method, such as String, Integer, etc. to turn it into Value comparison, so in general, equals compares whether the values ​​are equal.

Equals extension:
For equals, jdk gives some explanations.

The equals method implements the equivalence relationship on non-null object references:
(1). Reflexivity: For any non-null reference value x, x.equals(x) should return true.

(2). It is symmetric: for any non-null reference value x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

(3). Transitivity: For any non-null reference value x, y and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

(4). It is consistent: for any non-null reference value x and y, multiple calls to x.equals(y) always return true or always return false, and there is no information used in the setting of equals compared to the object being modified.

(5). For any non-empty reference value x, x.equals(null) should return false.

There is also something to note:
the equals class method Object implements the equality relationship with the greatest possible difference on the object; that is, for any non-empty reference value x and y, if and only if x and y refer to the same object (x == y has the value true), the method returns true.

Please note that whenever you override this method, you usually need to override the hashCode method in order to maintain the common contract of the hashCode method, which stipulates that equal objects must have equal hash codes.


Reference blog post link: https://blog.csdn.net/yujing1314/article/details/105898947

Guess you like

Origin blog.csdn.net/qq_43148688/article/details/106115210