Given a class like so:
class MyObject {
private String id1;
private String id2;
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof MyObject)) {
return false;
}
MyObject other = (MyObject) o;
return id1.equals(other.id1) || id2.equals(other.id2);
}
}
Notice that equality does not depend on both fields matching, either field works. What would be a suitable hashCode
implementation for this class?
It is perfectly legal for two objects to have the same hashcode. If two objects are equal (using the equals() method) then they have the same hashcode. If two objects are not equal then they cannot have the same hashcode.
hashCode in Java is a function that returns the hashcode value of an object on calling. It returns an integer or a 4 bytes value which is generated by the hashing algorithm. The process of assigning a unique value to an object or attribute using an algorithm, which enables quicker access, is known as hashing.
When two unequal objects have the same hash value, this causes a collision in the hash table, because both objects want to be in the same slot (sometimes called a bucket).
HashCode collisions Whenever two different objects have the same hash code, we call this a collision. A collision is nothing critical, it just means that there is more than one object in a single bucket, so a HashMap lookup has to look again to find the right object.
This is not a valid implementation of equals
.
Specifically, it violates the transitivity requirement.
As such, you can't implement hashCode
"correctly" either, aside from making all instances have the same hash code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With