Sobes.tech
Middle

Why are the hashCode methods and the comparison operator == overridden?

sobes.tech AI

Answer from AI

Overriding hashCode and the == operator (to compare objects by value rather than by reference) is necessary for the correct functioning of hash-based collections such as HashSet and HashMap.

  • == Operator: Defines when two objects are considered equal. By default, it compares references. Overriding it allows implementing logic to compare objects by their content or attributes.
  • hashCode Method: Returns an integer hash code for the object. If two objects are equal according to the == operator, their hash codes must be the same. The reverse is not necessarily true (two objects can have the same hash code but not be equal).

Violating this contract (equal objects having different hash codes) leads to incorrect behavior of hash-based collections: elements may be added multiple times where uniqueness is expected (HashSet), or they may not be found (HashMap).

Example:

class Person {
  final String name;
  final int age;

  Person(this.name, this.age);

  @override
  bool operator ==(Object other) {
    // Check if other is a Person
    if (identical(this, other)) return true;
    if (other.runtimeType != runtimeType) return false;
    // Compare attributes
    return other is Person && name == other.name && age == other.age;
  }

  @override
  int get hashCode => Object.hash(name, age); // Generate hash from attributes
}

void main() {
  final p1 = Person('Alice', 30);
  final p2 = Person('Alice', 30);
  final p3 = Person('Bob', 25);

  print(p1 == p2); // true (value comparison after override)
  print(p1 == p3); // false

  final peopleSet = {p1};
  print(peopleSet.contains(p2)); // true (search by hash and comparison)
}
Why are the hashCode methods and the comparison… - sobes.tech