Java equals() Method Guide

In Java, the equals() method is used to compare if two objects are equal. This method is inherited from the Object class, and therefore can be called by all classes. By default, the equals() method compares if two objects have the same reference, i.e. if they are the same object.

When we want to compare the content of two objects for equality, we need to override the equals() method. Typically, we need to override the equals() method in a custom class to implement custom object comparison logic.

The general steps for overriding the equals() method are as follows:

  1. Check if the parameter is null, if it is null, return false.
  2. Check if the objects are the same reference, if they are, return true.
  3. Check if the objects are of the same type, return false if they are not.
  4. Convert the parameter object to an object of the current class.
  5. Compare each property of the objects to see if they are equal. If all properties are equal, return true, otherwise return false.

Here is an example code demonstrating how to override the equals() method.

public class Person {
    private String name;
    private int age;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }

        Person person = (Person) obj;

        if (age != person.age) {
            return false;
        }

        return name.equals(person.name);
    }

    public static void main(String[] args) {
        Person person1 = new Person("Alice", 30);
        Person person2 = new Person("Alice", 30);

        System.out.println(person1.equals(person2)); // 输出为true
    }
}

In the code above, we have rewritten the equals() method of the Person class to compare the name and age properties of Person objects for equality. In the main method, we created two Person objects with the same name and age properties, so calling the equals() method returned true.

bannerAds