I have a custom SwingWorker
inner class. I found several times their hashcode are the same for different instances of it. Why is that? Normal?
EDIT:
The inner class I have is a subclass of the SwingWorker
class.
1) If two objects are equal (i.e. the equals() method returns true), they must have the same hashcode. 2) If the hashCode() method is called multiple times on the same object, it must return the same result every time. 3) Two different objects can have the same hash code.
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.
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.
Two same strings/value must have the same hashcode, but the converse is not true. There might be another string which can match the same hash-code, so we can't derive the key using hash-code. The reason for two different string to have the same hash-code is due to the collision.
Hash codes do not need to be different for different objects. The only requirement is that they must be the same for equal objects.
If it is a concern that your SwingWorker
inner classes produce identical hash codes, you could override the hashCode
method in your inner class to provide hash codes that suit your needs better. Of course you would need to override equals
as well to supply the matching logic to both methods:
final int workerId = 123;
SwingWorker<String,Object> myWorker = new SwingWorker<String,Object> {
@Override
public String doInBackground() {
...
}
@Override
protected void done() {
...
}
@Override
public int hashCode() {
return workerId;
}
@Override
public boolean equals(Object other) {
return other == this;
}
}
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