Overriding the equals() Method in Java for Object Comparison
In Java, the equals() method allows you to determine if two objects are equal. By default, equals() compares object references, which is not always the desired behavior. Overriding the equals() method enables you to define your own comparison logic.
Scenario:
You want to override the equals() method in a People class that has two data fields: name and age. You aim to compare people objects based on their names and ages.
Custom equals() Method:
To override the equals() method, you define it in the People class:
public boolean equals(People other) { // Null check and class check if (other == null || getClass() != other.getClass()) { return false; } // Downcast to People People otherPeople = (People) other; // Compare fields using == for primitive types (age) and equals() for objects (name) return name.equals(otherPeople.name) && age == otherPeople.age; }
Fixing the Primitive Type Comparison:
The original code attempted to use equals() to compare the age field, which is a primitive type. Primitive types have their own equality comparison operators (in this case, ==). Modifying age.equals(other.age) to age == other.age resolves this issue.
Usage Example:
Within the Main class, an ArrayList of Person objects is created. The equals() method is used to compare people and print the results:
ArrayList<Person> people = new ArrayList<>(); people.add(new Person("Subash Adhikari", 28)); // ... // Compare people objects for (int i = 0; i < people.size() - 1; i++) { for (int y = i + 1; y <= people.size() - 1; y++) { boolean check = people.get(i).equals(people.get(y)); // Print comparison result System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName()); System.out.println(check); } }
Output:
The program will print whether the compared people are equal or not. For example:
-- Subash Adhikari - VS - K false -- Subash Adhikari - VS - StackOverflow false -- Subash Adhikari - VS - Subash Adhikari true
The above is the detailed content of How to Override the equals() Method in Java for Accurate Object Comparison?. For more information, please follow other related articles on the PHP Chinese website!