Java hashcode () conflicts for objects that contain different but similar strings
When verifying the output data of the program, I determined that the hash codes of two different objects are the same To get this code, I used the following functions:
int getHash( long lID,String sCI,String sCO,double dSR,double dGR,String sSearchDate ) { int result = 17; result = 31 * result + (int) (lID ^ (lID >>> 32)); long temp; temp = Double.doubleToLongBits(dGR); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(dSR); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + (sCI != null ? sCI.hashCode() : 0); result = 31 * result + (sCO != null ? sCO.hashCode() : 0); result = 31 * result + (sSearchDate != null ? sSearchDate.hashCode() : 0); return result; }
Here are two example cases:
getHash( 50122,"03/25/2015","03/26/2015",4.0,8.0,"03/24/15 06:01" ) getHash( 51114,"03/24/2015","03/24/15 06:01" )
I think this problem arises because there are three very similar strings in my data. The difference of hash codes between strings a to B and B to C is the same, resulting in the same returned hash codes
IntelliJ's hashcode () implementation uses 31 as the multiplier of each variable, which contributes to the final hash code I wonder why one doesn't use different values for each variable (such as 33,37,41 (I mentioned in other posts when dealing with hash codes))? In my case, this will lead to the difference between my two objects
But I wonder if this will lead to problems in other situations?
Any thoughts or tips on this? thank you very much!
Solution
The hashcode () contract allows different objects to have the same hash code From documentation:
However, since your hash has a bunch of parameters, you can consider using objects Hash () instead of its own implementation:
@Override int getHash(long lID,String sSearchDate) { return Objects.hash(lID,sCI,sCO,dSR,dGR,sSearchDate); }
For example:
Objects.hash(50122,"03/24/15 06:01") Objects.hash(51114,"03/24/15 06:01")
The result is:
-733895022 -394580334