Middle
What are the rules for the equals and hashCode methods?
sobes.tech AI
Answer from AI
- If two objects are equal according to the
equals(Object)method, their hash codes (returned by thehashCode()method) must be the same. - If two objects are not equal according to the
equals(Object)method, their hash codes may be the same or different. It is good practice to ensure different hash codes for unequal objects for better performance of hash-based collections. - The
hashCode()method should return the same value for the same object across multiple calls, provided that no information used in the hash code calculation has changed. - Symmetry: for any objects
aandb, ifa.equals(b)istrue, thenb.equals(a)should also betrue. - Reflexivity: for any non-null object
a,a.equals(a)should betrue. - Transitivity: for any objects
a,b, andc, ifa.equals(b)istrueandb.equals(c)istrue, thena.equals(c)should also betrue. - Consistency: for any non-null objects
aandb, multiple invocations ofa.equals(b)should consistently returntrueorfalse, provided that no information used in theequals(Object)comparisons has changed.
Example implementation:
public class MyClass {
private int value;
private String name;
public MyClass(int value, String name) {
this.value = value;
this.name = name;
}
@Override
public boolean equals(Object o) {
// Check object identity
if (this == o) {
return true;
}
// Check object type
if (o == null || getClass() != o.getClass()) {
return false;
}
// Cast to the correct type
MyClass myClass = (MyClass) o;
// Compare fields
return value == myClass.value &&
Objects.equals(name, myClass.name); // Use Objects.equals to handle nulls
}
@Override
public int hashCode() {
// Use Objects.hash to generate hash code based on fields
return Objects.hash(value, name);
}
// Other methods...
}