In Java, when you override the equals()
method, it is crucial to also override the hashCode()
method to maintain the general contract between them. This ensures that objects that are considered equal will behave correctly when used in collections like HashSet
, HashMap
, or Hashtable
.
Let’s walk through a proper implementation of both methods using a College
class.
Overriding equals()
Method
Here's an example equals()
method that checks for object identity, type compatibility, and field equality based on the id
field:
java
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof College))
return false;
College other = (College) obj;
return Objects.equals(this.id, other.id);
}
This method ensures:
- Reflexivity: An object is equal to itself.
- Type safety: Compares only with instances of
College
. - Logical equality: Compares based on the
id
field.
Implementing a Consistent hashCode()
Method
To maintain the contract of hashCode()
(i.e., equal objects must have equal hash codes), we use the same field (id
) that’s used in the equals()
method:
java
@Override
public int hashCode() {
return Objects.hash(id);
}
The Objects.hash()
utility method computes a reliable hash code using the provided fields.
Full Example: College Class
java
import java.util.Objects;
public class College {
private final String id;
public College(String id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof College))
return false;
College other = (College) obj;
return Objects.equals(this.id, other.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
// Getters, setters, and other methods
}
Why This Matters
Failing to override hashCode()
when equals()
is overridden can result in unexpected behavior. For example:
java
Set<College> colleges = new HashSet<>();
colleges.add(new College("C101"));
System.out.println(colleges.contains(new College("C101"))); // false if hashCode isn't overridden
Without a consistent hashCode()
, even logically equal objects won't be found in hash-based collections.
Summary
- Always override
hashCode()
when you override equals()
. - Use the same fields for both methods.
Objects.hash(...)
simplifies generating robust hash codes.- Properly implementing both methods ensures reliable behavior in collections.