Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hashCode can be the same for different instances of an inner class?

Tags:

java

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.

like image 935
5YrsLaterDBA Avatar asked Sep 04 '13 14:09

5YrsLaterDBA


People also ask

Can Hashcode be same for the different objects?

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.

Can two classes have same Hashcode?

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.

Can Hashcode be same?

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.

Can Hashcode be same in Java?

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.


1 Answers

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;
   }
}
like image 51
Sergey Kalinichenko Avatar answered Nov 12 '22 20:11

Sergey Kalinichenko