2

在阅读一些代码时,我注意到一些开发人员使用按位异或运算符^来生成对象的哈希码。

这样做有什么意义?与其他获取/生成对象哈希码的方法相比,它是否具有一些优势?

这是一个代码示例。

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
}
4

1 回答 1

0

它必须是一个单一的数字,并且它在对象的任何成员的更多位上变化越大越好。

于 2020-11-22T22:43:31.393 回答