A. Mashreghi A. Mashreghi - 1 year ago 85
Java Question

Hashing function in HashTable vs HashMap?

I know the difference between HashTable and HashMap. However, both these classes seemingly are using a hash function to get the job done. Is there a difference between the hash function used in HashTable, and the hash function used in HashMap?

In particular, is there a difference between the hashing algorithm they use? What is the formula used to hash in these two classes?

Answer Source

java.util.Hashtable<K,V> is like java.util.Vector<T>. It's a class added to the SDK very early in development which has been superseded by HashMap<K,V> (as ArrayList<T> superseded Vector<T>).

So you simply shouldn't use it unless you require implicit synchronization of all the operations, which comes by default with Hashtable, but you can stil use Collections.synchronizedMap for that purpose or a ConcurrentHashMap<K,V>.

As stated in Javadoc:

As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

The hashing of the two classes should be the same, as they'll both use int Object::hashCode for their purpose.