Dart Set 如何比较项目? [复制]

2024-07-03

我刚刚塞了一堆MyClass里面一个Set在达特中。MyClass不实施Comparable,并且没有==运算符定义。它编译得很好。

为了这Set为了正确检测重复项,我是否必须实施Comparable接口,或者只是覆盖==操作员?


所有 Dart 类都派生于Object,这确实提供了operator == and hashCode. Object的默认实现检查对象identity;你的类的一个实例将仅与其自身进行比较。

如果您希望两个不同的实例能够比较相等,那么您需要:

  • 实施operator == and hashCode在您的自定义课程中。Set的默认实现是LinkedHashSet,其中不使用Comparable。 (有一个SplayTreeSet执行 https://api.dart.dev/stable/2.8.4/dart-collection/SplayTreeSet-class.html确实使用Comparable但是,查找和插入的时间复杂度为 O(log n) 而不是 O(1)。)
  • 或者使用LinkedHashSet构造函数 https://api.dart.dev/stable/dart-collection/LinkedHashSet/LinkedHashSet.html or the HashSet构造函数 https://api.dart.dev/stable/dart-collection/HashSet/HashSet.html并传递适当的回调以进行相等和哈希代码计算。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Dart Set 如何比较项目? [复制] 的相关文章

随机推荐