2

While reading some code, it came to my attention that some developers use the bitwise XOR operator, ^, to generate the hashcode of an object.

What's the point of doing it like this? Does it have some advantages over other methods to get/generate the hashcode of an object?

Here is a code example.

class Student {
  final String name;
  final int age;

  Student(this.name, this.age);

  @override
  bool operator ==(other) {
    return (other is Student) && other.name == name && other.age == age;
  }

  @override
  int get hashCode => age.hashCode ^ name.hashCode; // <-- Here
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
korchix
  • 1,445
  • 1
  • 19
  • 22

1 Answers1

0

It has to be a single number, and the more it varies on more of the bits of any member of the object, the better.

Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70
  • Do you mean the result of the bitwise XOR has to be a single number ? and why / in which case will you choose this to generate the hashcode ? – korchix Nov 23 '20 at 23:37
  • This answers it pretty well: https://stackoverflow.com/questions/20577606/whats-a-good-recipe-for-overriding-hashcode-in-dart – Randal Schwartz Nov 24 '20 at 01:45