Junior
What is the difference between the equals and hashCode methods in Java?
sobes.tech AI
Answer from AI
The equals method is used to compare objects for equality of their content, while hashCode returns an integer value that represents the object's hash code.
Main differences:
- Purpose:
equalsfor determining logical equality,hashCodefor generating a hash code (usually for use in hash data structures). - Result:
equalsreturns aboolean(true or false),hashCodereturns anint. - Contract: If two objects are equal according to
equals, theirhashCodemust be the same. The reverse is not true: objects with the samehashCodecan have different contents (collision). - Usage:
equalsis used for pairwise comparison of objects.hashCodeis used in hash-based collections (e.g.,HashSet,HashMap) for quick object lookup.
Example:
// Example class
class MyObject {
private int id;
private String name;
public MyObject(int id, String name) {
this.id = id;
this.name = name;
}
// Override equals
@Override
public boolean equals(Object o) {
if (this == o) return true; // Identity check
if (o == null || getClass() != o.getClass()) return false; // Type and null check
MyObject myObject = (MyObject) o; // Type casting
return id == myObject.id && Objects.equals(name, myObject.name); // Field comparison
}
// Override hashCode
@Override
public int hashCode() {
return Objects.hash(id, name); // Generate hash code based on fields
}
}
It is important to override both methods (equals and hashCode) together, if one of them is overridden, to avoid breaking the contract and to ensure correct operation of collections.