Java hashcode() string conflict
•
Java
I know little about hash codes I found that this code can print out collisions
Can you tell me what collision is and how to reduce it? Why do we use hash codes?
public static int getHash(String str,int limit) { int hashCode = Math.abs(str.hashCode()%(limit)); return hashCode; } /** * @param args */ public static void main(String[] args) { int hashLimit = 10000; int stringsLimit = 10000; String[] arr = new String[hashLimit]; List<String> test = new ArrayList<String>(); Random r = new Random(2); for ( int i = 0 ; i < stringsLimit ; i++ ) { StringBuffer buf = new StringBuffer(""); for ( int j = 0 ; j < 10 ; j++ ) { char c = (char)(35+60*r.nextDouble()); buf.append(c); } test.add(buf.toString()); //System.out.println(buf.toString()); } int collisions = 0; for ( String curStr : test ) { int hashCode = getHash(curStr,hashLimit); if ( arr[hashCode] != null && !arr[hashCode].equals(curStr) ) { System.out.println("collision of ["+arr[hashCode]+"] ("+arr[hashCode].hashCode()+" = "+hashCode+") with ["+curStr+"] ("+curStr.hashCode()+" = "+hashCode+")"); collisions++; } else { arr[hashCode] = curStr; } } System.out.println("Collisions: "+collisions); }
Solution
The conflict is that two unequal objects have the same hash code They are facts in life - you need to deal with it
Because they can basically press the key quickly to find the value The hash table can use the hash code to quickly download the possible key matching set to a very small set (usually only one). At this time, you need to check the actual key equality
You should never assume that two hash codes are equal, which means that their derived objects are equal Only the opposite: assuming a correct implementation, if two objects give different hash codes, they are not equal
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码