我有一个声明如下的变量:
val done = HashSet<StudentProgrammeState>()
Run Code Online (Sandbox Code Playgroud)
在处理结束时,检查如下:
if (done.distinctBy { it.hashCode() }.size < done.size ) {
println("Duplicate states were evaluated.")
}
Run Code Online (Sandbox Code Playgroud)
每次运行都会显示此消息.既然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)
Run Code Online (Sandbox Code Playgroud)
Equals这里不直接检查hashCode,instances但该测试应该对应于无序集合相等.
对于studentModuleInstance:
typealias StudentModuleInstance = Pair<Module, Int>
Run Code Online (Sandbox Code Playgroud)
由于Pair<>是内置的,data class它应该有一个Kotlin生成equals和hashcode方法.
program对于所考虑的所有实例,值都设置为相同.
HashSet.add()提供此合同:
如果指定的元素尚不存在,则将其添加到此集合中.更正式地,如果此集合不包含元素e2(e == null?e2 == null:e.equals(e2)),则将指定元素e添加到此集合.如果此set已包含该元素,则调用将保持set不变并返回false.
特别hashCode是没有提到.hashCode唯一性与add方法无关:具有相同哈希码的多个项目将进入哈希集.
具有相同hashCode但不等于的项目将最终位于同一个存储桶中,这会降低get()这些项目的性能.但除此之外,hashCode并不重要.
| 归档时间: |
|
| 查看次数: |
1045 次 |
| 最近记录: |