To implement custom equality in Java, the equals() method should be overridden to compare the business-relevant fields of an object rather than comparing object references. A proper implementation checks for self-comparison, verifies the object type, and then compares the fields that determine logical equality. Whenever equals() is overridden, hashCode() must also be overridden to maintain the contract required by hash-based collections.
Key Points: • equals() should compare the actual content or business attributes of objects, not their memory addresses. • Use Objects.equals() for null-safe field comparisons and improved readability. • Always override hashCode() along with equals() to ensure correct behavior in HashMap, HashSet, and other hash-based collections.
Example: In an Employee class, two employee objects may be considered equal if they have the same employeeId, even if they are different object instances in memory. This allows collections to treat logically identical employees as the same entity.
Code Example:
import java.util.Objects;
class Employee {
private int employeeId;
private String name;
public Employee(int employeeId, String name) {
this.employeeId = employeeId;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Employee other = (Employee) obj;return employeeId == other.employeeId &&
Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(employeeId, name);
}
}Interview Tip: A concise interview answer is: To implement custom equality, override equals() to compare the fields that define logical equality, perform proper null and type checks, and use Objects.equals() for safe comparisons. Always override hashCode() together with equals() to maintain consistency in hash-based collections.