Can hashcode collision affect equals in Java? -


the hashcode() contract allows different objects have same hash code. document:

it not required if 2 objects unequal according equals(java.lang.object) method, calling hashcode method on each of 2 objects must produce distinct integer results.

at same time, in eclipse, if use function source->generate hashcode() , equals, thing this:

package test1;  public class j1 {     private int a;     private int b;      @override     public int hashcode() {         final int prime = 31;         int result = 1;         result = prime * result + a;         result = prime * result + b;         return result;     }      @override     public boolean equals(object obj) {         //compare hashcode         if (this == obj)             return true;         if (obj == null)             return false;         if (getclass() != obj.getclass())             return false;         j1 other = (j1) obj;         if (a != other.a)             return false;         if (b != other.b)             return false;         return true;     } } 

in function equals(), first compare hashcode of this , obj, if have same hashcode, equals() returns true. document says 2 different objects may have different hashcode, affect correctness of equals(). can't figure out problem.

in function equals(), first compare hashcode of , obj, if have same hashcode, equals() returns true.

no, if (this == obj) does not compare hash code of 2 objects. checks whether this , obj referring same object, in case must equal (since object should equal itself), following logic of equals doesn't need executed in case.

on other hand, if this != obj, this , obj referring different objects, may still equal each other, depending on logic of equals. if logic of equals returns true, contract requires must have same hashcode().


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -