equals
but not hashCode
KT-W1028The class overrides the equals()
method, but does not override the hashCode()
method.
When a class overrides the equals()
method, it should also override the hashCode()
method to maintain the contract between these two methods.
If the hashCode()
method is not overridden, it can lead to inconsistent behavior when the class is used in data structures like HashSet
or HashMap
.
When these instances are used as keys in a HashMap
or inserted into a HashSet
, the hashCode()
method is used to generate a hash value for each instance.
If two instances are considered equal based on the equals()
method but have different hash values, they will be treated as distinct keys in these data structures.
To fix this issue, the class should also override the hashCode()
method and ensure that it follows the general contract of these methods.
The hashCode()
method should generate the same hash value for instances that are considered equal according to the equals()
method.
class Foo {
override fun equals(other: Any?): Boolean {
eturn super.equals(other)
}
}
class Person(val name: String, val age: Int) {
override fun equals(other: Any?): Boolean {
// implementation of equals method
}
override fun hashCode(): Int {
// implementation of hashCode method
}
}