Home > Java > javaTutorial > body text

How to correctly compare objects for equality in Java: overriding and overriding the equals(Object) method

WBOY
Release: 2024-01-11 17:18:05
Original
512 people have browsed it

How to correctly compare objects for equality in Java: overriding and overriding the equals(Object) method

The equals(Object) method in Java is a method used to compare the equality of two objects. In Java classes, the equals method is inherited from the Object class by default, and it simply compares the reference values ​​of two objects. However, we often need to compare objects for equality in a custom way, which requires overriding the equals method in a subclass.

In order to correctly compare objects for equality, we must follow several rules. First, the equals method must satisfy reflexivity, which means that an object must be equal to itself. Secondly, the equals method must satisfy symmetry, that is, if object A is equal to object B, then object B and object A must also be equal. Finally, the equals method must satisfy transitivity, that is, if object A is equal to object B, and object B is equal to object C, then object A and object C must also be equal.

In order to override and override the equals method, we need to consider the following key points.

First, we need to ensure that the signature of the equals method is consistent with the equals method in the Object class. The signature of the equals method should be: public boolean equals(Object obj). This means we need to accept a parameter of type Object and return a Boolean value.

Secondly, we need to perform type checking to ensure that the incoming parameter is an object that matches the current object type. This can be achieved by using the instanceof keyword. If the type check fails, we can directly return false.

Then, we need to convert the incoming parameters to the type of the current object and compare the equality of each attribute. In this process, we must follow the implementation convention of Java's equals method, that is, use the equals method to compare the properties of objects instead of using the "==" operator.

When comparing attribute values, we need to consider the situation of null references. If the property value is null, we can use the equals method of the Objects class for comparison, which will correctly handle the null reference situation. In addition, for basic type attributes, we can directly use the "==" operator for comparison.

Finally, we need to ensure that the equals method overrides the hashCode method. According to the Java specification, if two objects are equal, their hashCode methods must return the same value. This is to ensure that objects are stored and retrieved correctly when using data structures such as hash tables.

The following is an example that shows how to override the equals method:

public class Person {
    private String name;
    private int age;
  
    // 省略构造方法、getter和setter方法
  
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Person)) {
            return false;
        }
        Person other = (Person) obj;
        return Objects.equals(this.name, other.name) && this.age == other.age;
    }
  
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
  
    // 省略其他方法
}
Copy after login

In the above example, we override the equals method to compare the equality of the name and age properties of the Person object sex. At the same time, we also overridden the hashCode method to ensure that equal objects have the same hash code.

To summarize, by correctly rewriting and overriding the equals method, we can ensure that we get the correct results when comparing objects for equality. It should be noted that the rewriting of the equals method must satisfy properties such as reflexivity, symmetry, and transitivity, and the hashCode method also needs to be rewritten. By following these rules, we can ensure that we get the correct results when using equality comparisons of objects.

The above is the detailed content of How to correctly compare objects for equality in Java: overriding and overriding the equals(Object) method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!