在Dart中覆盖哈希码的好方法是什么? [英] What's a good recipe for overriding hashcode in Dart?

查看:218
本文介绍了在Dart中覆盖哈希码的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己想覆盖对象的哈希码和==,并且我想知道是否存在实现依赖于多个属性的哈希码的最佳实践,并且似乎存在一些Dart特定的注意事项

I find myself wanting to override hashcode and == for an object, and I'm wondering if there are best practices for how to implement a hashcode that depends on multiple attributes, and it seems like there are some Dart-specific considerations.

最简单的答案是将所有属性的哈希值进行XOR运算,这可能还不错。在Dart Up and Running中还有一个示例,位于 https:/ /www.dartlang.org/docs/dart-up-and-running/contents/ch03.html

The simplest answer would be to XOR the hashes of all the attributes together, and it's probably not too bad. There's also an example in Dart Up and Running at https://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html

  // Override hashCode using strategy from Effective Java, Chapter 11.
 int get hashCode {
   int result = 17;
   result = 37 * result + firstName.hashCode;
   result = 37 * result + lastName.hashCode;
   return result;
 }

但这似乎期望截断整数语义并且在Dart中溢出JS整数似乎对哈希很不利。

but that seems like it expects truncating integer semantics and in Dart overflowing the range of JS integers seems bad for hashing.

我们也可以这样做,并且每次操作后都将其截断为32位。

We could also do that and just truncate to 32 bits after each operation.

对于我的应用程序,该集合的预期大小非常小,几乎可以做任何事情,但是令我惊讶的是,没有看到适用于一般情况的标准配方。有人对此有任何经验或丰富经验吗?

For my application the expected size of the set is very small and almost anything would do, but I'm surprised not to see a standard recipe for the general case. Does anyone have any experience or strong experience with this?

推荐答案

颤音软件包提供了辅助功能 hash2 hash3 等,简化了实现 hashCode 的任务,并保证它在Dart VM 下正常运行

The quiver package provides helper functions hash2, hash3, etc., which simplify the task of implementing hashCode, with some assurance that it works properly under the Dart VM and when compiled to JavaScript.

import 'package:quiver/core.dart';

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  bool operator ==(o) => o is Person && name == o.name && age == o.age;
  int get hashCode => hash2(name.hashCode, age.hashCode);
}

另请参见这篇文章进行了更长的讨论。

Also see this post for a slightly lengthier discussion.

这篇关于在Dart中覆盖哈希码的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆