Tell me about the equals and hashCode method contracts in Java.
sobes.tech AI
Answer from AI
-
Reflexivity: for any non-null reference value
x,x.equals(x)should returntrue. -
Symmetry: for any non-null reference values
xandy,x.equals(y)should returntrueif and only ify.equals(x)returnstrue. -
Transitivity: for any non-null reference values
x,y, andz, ifx.equals(y)returnstrueandy.equals(z)returnstrue, thenx.equals(z)should returntrue. -
Consistency: for any non-null reference values
xandy, multiple invocations ofx.equals(y)should consistently returntrueorfalse, provided no information used inequalscomparisons on the objects is modified between calls. -
For any non-null reference value
x,x.equals(null)should returnfalse. -
If two objects are equal according to the
equals(Object)method, then calling thehashCodemethod on each of the two objects must produce the same integer result. -
It is not required that if two objects are unequal according to the
equals(java.lang.Object)method, then calling thehashCodemethod on each of the two objects must produce distinct integer results. However, programmers should be aware that producing distinct hash codes for unequal objects may improve the performance of hash tables.
It is important to override both equals and hashCode methods if one of them is overridden to maintain the contract. Using equals without overriding hashCode can lead to incorrect behavior of collections that use hashing (e.g., HashMap, HashSet).
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true; // Reflexivity
if (o == null || getClass() != o.getClass()) return false; // Null check and type check
Person person = (Person) o;
return age == person.age &&
Objects.equals(name, person.name); // Content comparison
}
@Override
public int hashCode() {
return Objects.hash(name, age); // Hash generation based on fields
}
}