1, inheritance and implementation of the difference
Hashtable is based on the old dictionary class, complete the map interface; HashMap is an implementation of the map interface introduced by Java 1.2 (HashMap inherited from Abstractmap, Abstractmap completes the map interface).
2. Different thread safety
The Hashtable method is synchronous, HashMap is not synchronized, so in multi-threaded occasions to manually synchronize HashMap.
3, the processing of NULL is different
Hashtable does not allow null values (neither key nor value), HashMap allows null values (both key and value can be)。 That is, Hashtable does not allow null values in fact, in the compilation period will not be any different, will still be executed, but at the time of the runtime Hashtable set in the back of the null pointer exception. HashMap allows null values to mean that a value of one or more keys corresponds to NULL. When the Get () method returns a null value, it can indicate that the key is not in the HashMap, or that the value corresponding to the key is null. Therefore, the get () method cannot be used in HashMap to determine whether a key exists in HashMap.instead, the ContainsKey () method should be used to determine。
4. Different methods
Hashtable has acontains (object value), the same function as the Containsvalue (object value)。
5.Hashtable using Enumeration,hashmap with iterator。
6, in HashtableThe default size of the hash array is 11, and the increment is old*2+1. The default size of the hash array in HashMap is 16, and must be a 2 index。
7.hash values are used differently, Hashtable directly uses the object's Hashcode, and the code is like this:
inthash =Key.hashcode (); intIndex = (hash & 0x7FFFFFFF)%tab.length; Instead, HashMap recalculates the hash value and uses and replaces the modulo:inthash =Hash (k); inti =indexfor (hash, table.length); Static inthash (Object x) {inth =X.hashcode (); H+ = ~ (H << 9); H^= (H >>> 14); H+ = (H << 4); H^= (H >>> 10); returnh; }Static intIndexfor (intHintlength) {returnH & (Length-1); }
The difference between Java Hashtable and Hastmap