About the comparison of "==" and "equals () method"

1) For ==, compare whether the values ​​are equal

  • If it is a basic data type, it is compared whether the stored "value" is equal in size;

  • If acting on a variable of reference type, the address of the pointed-to object is compared

2) For the equals method, note that the equals method cannot be applied to variables of basic data types. Equals inherits the Object class and compares whether it is the same object. The
unrewritten equals () method:

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

If the equals method is not rewritten, the address of the object pointed to by the variable of the reference type is compared;

If classes such as String and Date rewrite the equals method, the content of the pointed-to object is compared.
    
Let's look at a small program:

package test;

public class student{
    String name;
    int age;
    boolean sex;

    @Override
    public boolean equals(Object obj) {
        if(this == obj){
            return true;
        }
        if(obj instanceof student){
            student student=(student)obj;
            if(this.name.equals(student.name)&&this.age==student.age&&this.sex == student.sex){
                return true;
            }
        }
        return false;
    }
}
package test;

public class test {
    public static void main(String[] args) {
        student p1 = new student();
        p1.name="a";
        p1.age=10;
        p1.sex=false;

        student p2 = new student();
        p2.name="a";
        p2.age=10;
        p2.sex=false;
        System.out.println(p1.equals(p2));
    }
}

Output result: true , here we compare the three attribute values ​​of student by rewriting equals (), as long as the three attributes are the same, we think that the two objects are equal, if not rewritten, then equals () judges the memory of the object The address value obviously does not meet our requirements. Let's
look at the simple memory diagram:

Insert picture description here
As long as they are not the same object, then the addresses they store in memory must be inconsistent, even if all their attributes are the same, so we generally have to rewrite equals () when comparing objects, otherwise the comparison is meaningless.

Published 39 original articles · won praise 1 · views 4620

Guess you like

Origin blog.csdn.net/thetimelyrain/article/details/99697654