Home  >  Article  >  Java  >  What are the functions of equals() function and '=='?

What are the functions of equals() function and '=='?

王林
王林forward
2020-07-10 16:59:393442browse

What are the functions of equals() function and '=='?

First of all, let’s take a look at their differences:

(Recommended learning: java entry program)

  • The equals() method is used to compare whether the contents of two objects are equal. Since all classes inherit from the java.lang.Object class, it is applicable to all objects, if this method is not overridden. , the method still called is the method in the Object class, but the equals method in Object returns the judgment of ==;

  • "==" compares the variable (stack) memory The (heap) memory address of the object stored in is used to determine whether the addresses of two objects are the same, that is, whether they refer to the same object.

equals() function

equals() function is used to determine whether two objects are equal.

equals() is defined in Object.java of JDK. Distinguish whether two objects are equal by judging whether their addresses are equal (that is, whether they are the same object). The source code is as follows:

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

Since the equals() method is defined in Object.java, this means that all Java classes implement the equals() method, and all classes can compare two objects through equals(). Whether the objects are equal.

However, we have already said that using the default "equals()" method is equivalent to the "==" method. Therefore, we usually override the equals() method: if the contents of the two objects are equal, the equals() method returns true; otherwise, returns fasle.

The following is divided into 2 categories based on "whether the class covers the equals() method".

  • If a class does not cover the equals() method, when it compares two objects through equals(), it actually compares whether the two objects are the same object. At this time, it is equivalent to comparing the two objects through "==".

  • We can override the equals() method of the class to let equals() compare whether two objects are equal through other methods. The usual approach is: if the contents of the two objects are equal, the equals() method returns true; otherwise, returns fasle.

The following is an example to illustrate the above two situations:

1. The case of not covering the equals() method

public class EqualsTest {
    public static void main(String[] args) {
        // 新建2个相同内容的Person对象,
        // 再用equals比较它们是否相等
        User user1 = new User("James", 100);
        User user2 = new User("James", 100);
        System.out.printf("比较结果:" + user1.equals(user2));
    }
 
    /**
     * @desc User类。
     */
    static class User {
        int age;
        String name;
 
        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }
 
        public String toString() {
            return name + " - " + age;
        }
    }
}

Running results:

false

Result analysis:

We use user1.equals(user2) to "compare whether user1 and user2 are equal". In fact, the equals() method of Object.java is called, that is Called (user1==user2).

It compares "whether p1 and p2 are the same object". From the definitions of user1 and user2, we can see that although they have the same content, they are two different objects, so the return result is false.

(Video tutorial recommendation: java video tutorial)

2. Overriding the equals() method

Modify the above EqualsTest and overwrite the equals( )Method:

public class EqualsTest {
    public static void main(String[] args) {
        // 新建2个相同内容的Person对象,
        // 再用equals比较它们是否相等
        User user1 = new User("James", 100);
        User user2 = new User("James", 100);
        System.out.printf("比较结果:" + user1.equals(user2));
    }
 
    /**
     * @desc User类。
     */
    static class User {
        int age;
        String name;
 
        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }
 
        public String toString() {
            return name + " - " + age;
        }
 
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            User other = (User) obj;
            if (age != other.age)
                return false;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }
    }
}

Running results:

true

Result analysis: We rewrote User’s equals() function in EqualsTest.java: When the name and age of two User objects are equal , then returns true. Therefore, the running result returns true.

== Function

"==": Its function is to determine whether the addresses of two objects are equal. That is to determine whether the reference object is the same object in the heap pointed to. We know that all new objects are in the heap. The references to objects are stored in the stack, specifically in the stack frame. Let's look at the following piece of code:

public static void main(String[] args) {
        User user1 = new User("James", 100);
        User user2 = new User("James", 100);
        System.out.println("user1.equals(user2):" + user1.equals(user2));
        System.out.println("user1==user2:" + (user1==user2));
}

Output result:

user1.equals(user2):true
user1==user2:false

points to two objects in the heap Blocks are in different areas, so when compared with "==", false is returned.

The above is the detailed content of What are the functions of equals() function and '=='?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete