Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is alternative hashing for String keys in Java 8?

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?

like image 525
Pramod Kumar Avatar asked Aug 14 '12 05:08

Pramod Kumar


People also ask

What is hash code of string in Java?

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]

Can you hash a string?

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.

Can two keys have same hashCode in Java?

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.


1 Answers

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);
}
like image 58
mankadnandan Avatar answered Oct 02 '22 20:10

mankadnandan