Java 8 is providing alternative hashing for String keys to improve performance when a large number of key hash code collisions are encountered. Can anybody explain what is that and how it will work?
Java String hashCode() Method The hashCode() method returns the hash code of a string. The hash code for a String object is computed like this: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
Hashing is the process of transforming any given key or a string of characters into another value. This is usually represented by a shorter, fixed-length value or key that represents and makes it easier to find or employ the original string. The most popular use for hashing is the implementation of hash tables.
It's perfectly legal for two unequal objects to have the same hash code. It's used by HashMap as a "first pass filter" so that the map can quickly find possible entries with the specified key. The keys with the same hash code are then tested for equality with the specified key.
To bring more relevance to this question, the alternative hashing has been removed from JDK 8. Check out :
http://docs.oracle.com/javase/8/docs/technotes/guides/collections/changes8.html
http://openjdk.java.net/jeps/180
It is interesting to note that once the number of items in a hash bucket grows beyond a certain threshold, that bucket will switch from using a linked list of entries to a balanced tree.
The hash(Object key) function in the HashMap has been revised to follows with no special treatment to String objects:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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