【发布时间】:2019-03-21 16:42:21
【问题描述】:
我已经覆盖了 java 对象的 equals 方法。 (实际上是 kotlin 中的对象,但它很容易理解,我只是重写了 equals 方法)。但现在为了维护 equals 合同,我还应该重写 hashcode 方法。但我不确定如何为适合 equals 方法的哈希码实现。这是我目前所拥有的:
data class AddressModel(
var id_address: Int = 0,
var id_country: Int = 0,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AddressModel)
return false
else {
if (other.id_address == this.id_address)
return true
}
return false
}
}
编译器强烈建议我重写 hashCode 方法。但我不明白要实施什么。在 equals 覆盖中,我只是想检查 addressModel 是否与另一个具有相同的 Id,如果有,那么我假设它是相等的。
这是我目前所拥有的:
override fun hashCode(): Int {
return Objects.hash(id_address, id_country);
}
但我认为这样更好:
override fun hashCode(): Int {
return Objects.hash(id_address); //base hash off same as equals the id_address
}
这是我推荐的阅读方式,但这是什么意思?如果我添加了更多的类字段,我还需要向 Objects.hash 方法添加更多的字段吗?我更喜欢旧的 skool 方法,因为这个调用需要 android api 19,而且我支持较低的 (api 16)。
要清楚,我明白如果我不覆盖哈希码和 equals 那么每个实例,例如“new AddressModel(707, 867)”,将有不同的哈希码。然后例如HashMap会认为这些对象是不同的并且在计算存储哈希时不等于替换它们。但我只是不知道在 hashCode 实现中放什么。你可以用 kotlin 或 java 给我看,没问题。
更新:这就足够了:
override fun hashCode(): Int { return id_address.hashCode() }
【问题讨论】:
-
根据公认的answer 如果你有两个对象是 .equals(),但有不同的哈希码,你就输了!
-
我已经说过同样的话。我问你能帮我知道如何实现 hashCode()
-
我可以这样做:覆盖有趣的 hashCode(): Int { return id_address.hashCode()
-
注意:您可以将 'equals' 方法简化为单行:覆盖 fun equals(other: Any?) = this === other || (其他是 AddressModel && id_address == other.id_address)。