kotlin - 在 Kotlin 中,HashSet 包含通过哈希重复的元素
问题描述
我有一个声明如下的变量:
val done = HashSet<StudentProgrammeState>()
在处理结束时,检查如下:
if (done.distinctBy { it.hashCode() }.size < done.size ) {
println("Duplicate states were evaluated.")
}
每次运行都会出现此消息。既然done
是 a HashSet
,它怎么可能包含多个与 不同的项目HashCode
?
以下是 的相等方法StudentProgrammeState
:
class StudentProgrammeState(val program: Program) {
val instances = HashSet<StudentModuleInstance>()
override fun equals(other: Any?): Boolean {
if (!(other is StudentProgrammeState)) return false
return (other.program == program) &&
(other.instances.containsAll(instances) &&
instances.containsAll(other.instances))
}
override fun hashCode() = Objects.hash(program, instances)
Equals
这里不直接检查hashCode
ofinstances
但该测试应该对应于无序集相等。
对于 studentModuleInstance:
typealias StudentModuleInstance = Pair<Module, Int>
由于Pair<>
是内置的data class
,它应该有一个 Kotlin 生成equals
和hashcode
方法。
对于所考虑的所有实例,的值program
设置为相同。
解决方案
HashSet.add()提供了这个合约:
如果指定的元素尚不存在,则将其添加到此集合中。更正式地说,如果此集合不包含元素 e2,则将指定的元素 e 添加到此集合中,使得 (e==null ? e2==null : e.equals(e2))。如果该集合已包含该元素,则调用将保持该集合不变并返回 false。
特别hashCode
是没有提到。hashCode 唯一性与 add 方法无关:具有相同哈希码的多个项目将进入一个哈希集。
具有相同 hashCode 但不等于的项目将最终在同一个存储桶中,这会降低get()
这些项目的性能。但除此之外,hashCode 并不重要。
推荐阅读
- reactjs - 使用 React 以编程方式观察 Recoil 的变化
- azure-active-directory - Azure 函数托管标识到 Azure Sql - 用户登录失败
' - ghostscript - 如何区分带有嵌入书签的pdf文件?
- video - 需要将来自 Garmin 行车记录仪的多个 MP4 与遥测连接起来
- macos - 如何复制苹果使用的默认区域设置?
- python - 为什么当我使用“随机播放”时,它会随机播放我的数据,但我的大部分数组都返回零?
- python - scipy曲线拟合中的回归系数
- javascript - 使用 Python 抓取网页动态内容(动态 HTML/Javascript 表格)
- html - 在 BootstrapVue 中使用卡片时,有没有办法在卡片图像中添加重叠图像?
- c# - 如何在保存之前附加新实体?