Home  >  Article  >  Java  >  What does equals mean in java

What does equals mean in java

下次还敢
下次还敢Original
2024-04-27 00:33:15974browse

The equals() method is an object comparison method in Java, used to determine the equality of two objects. If equal, it returns true, otherwise it returns false. It can be used to compare whether the property values ​​of objects are the same. Custom equality comparison is usually implemented by overriding the equals() method. The steps to override the equals() method are: declare the equals() method, use if-else statements to compare the object's attribute values, and return true if they are equal, otherwise return false.

What does equals mean in java

What is the equals() method?

The equals() method is a member method of the Object class in Java, used to compare the equality of two objects.

Function:

The equals() method determines whether two objects are equal. If equal, it returns true, otherwise it returns false.

Usage:

The equals() method is usually used to compare whether the attribute values ​​​​of two objects are the same. The syntax is as follows:

<code class="java">public boolean equals(Object obj)</code>

Among them, obj is the object to be compared.

Note: The

  • equals() method is a member method of the Object class, so all Java objects inherit this method.
  • The equals() method compares the memory address of the object by default, that is, reference equality.
  • Custom equality comparison can be implemented by overriding the equals() method.

Steps to override the equals() method:

  1. Declare the equals() method in the class to be overridden.
  2. Use if-else statements to compare whether the attribute values ​​of objects are equal.
  3. If equal, return true; otherwise, return false.

Example:

<code class="java">public class Person {
    private String name;
    private int age;
    
    public boolean equals(Object obj) {
        if (obj instanceof Person) {
            Person other = (Person) obj;
            return name.equals(other.name) && age == other.age;
        }
        return false;
    }
}</code>

The above is the detailed content of What does equals mean in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn