Overriding the Equals Method in Java
In Java, the equals method is responsible for determining whether two objects are equal. By default, the equals method compares object references, which is not the desired behavior for many custom classes. To override the equals method and define custom equality semantics, the following guidelines should be followed:
Solution:
The provided code attempted to compare an Integer field (age) using the equals method, which is intended for Strings only. To correct this, the equality check for the age field should be replaced with a comparison using the == operator:
... } else { People otherPeople = (People) other; result = name.equals(other.name) && other.age == age; } ...
Usage:
The following code demonstrates how to use the overridden equals method:
... // Add several Person objects to an ArrayList people.add(new Person("Subash Adhikari", 28)); people.add(new Person("K", 28)); people.add(new Person("StackOverflow", 4)); people.add(new Person("Subash Adhikari", 28)); // Compare each pair of Person objects using the overridden equals method 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)); System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName()); System.out.println(check); } } ...
This code will produce the following output:
-- Subash Adhikari - VS - K false -- Subash Adhikari - VS - StackOverflow false -- Subash Adhikari - VS - Subash Adhikari true -- K - VS - StackOverflow false -- K - VS - Subash Adhikari false -- StackOverflow - VS - Subash Adhikari false
This output demonstrates that the overridden equals method is correctly comparing the Person objects based on their name and age fields.
The above is the detailed content of How to Properly Override the equals() Method in Java for Custom Object Comparisons?. For more information, please follow other related articles on the PHP Chinese website!