在Kotlin中,哈希集包含哈希重复的元素
我有一个变量声明如下:在Kotlin中,哈希集包含哈希重复的元素,kotlin,set,Kotlin,Set,我有一个变量声明如下: val done = HashSet<StudentProgrammeState>() if (done.distinctBy { it.hashCode() }.size < done.size ) { println("Duplicate states were evaluated.") } Equals此处不直接检查实例的hashCode,但该测试应对应于无序集相等 对于studentModuleInstance: typealias
val done = HashSet<StudentProgrammeState>()
if (done.distinctBy { it.hashCode() }.size < done.size ) {
println("Duplicate states were evaluated.")
}
Equals
此处不直接检查实例的hashCode
,但该测试应对应于无序集相等
对于studentModuleInstance:
typealias StudentModuleInstance = Pair<Module, Int>
typealias StudentModuleInstance=Pair
由于Pair
是一个内置的数据类
,因此它应该有一个生成的Kotlinequals
和hashcode
方法
对于所考虑的所有实例,程序的值设置为相同。提供了此合同:
如果指定的元素尚未存在,则将其添加到此集合。
更正式地说,如果该集合
不包含(e==null?e2==null:e.equals(e2))的元素e2。
如果此集合已经包含该元素,则调用将离开该集合
未更改并返回false
特别是,没有提到hashCode
。哈希代码唯一性与add方法无关:具有相同哈希代码的多个项将进入一个哈希集中
具有相同hashCode但不等于的项最终将位于同一个bucket中,这会降低这些项的get()
性能。但是除此之外,hashCode并不重要。HashSet将具有相同hash代码的不同项放在同一个bucket中,但是如果它们不相等,它们仍然都会出现在bucket中。这是哈希集的正确行为,无论使用何种语言。散列被用作快速查找的性能优化。实际上,它只是java方法描述的副本:实际上,它只是java方法。检查链接:)
typealias StudentModuleInstance = Pair<Module, Int>