1, the two inherit the direct parent class is different: Hashtable inherit from the Dictiionary,hashmap inherit from Abstractmap, this difference can be clearly seen through the source code of both:
public class hashmap<k,v> extends abstractmap<k,v> implements Map<k,v>, Cloneable, Serializablepublic class hashtable<k,v> extends dictionary<k,v> implements MAP<K,V> Cloneable, java.io.Serializable
2.
The Put method of Hashtable is as follows:
Public synchronized v put (K key, V value) { //Make sure the value was not null if (value = = null) { throw new NullPointerException (); } Makes sure the key is not already in the Hashtable. Entry tab[] = table; int hash = Key.hashcode (); int index = (hash & 0x7FFFFFFF)% Tab.length; for (Entry e = Tab[index]; E! = null; e = e.next) { if (E.hash = = hash) && e.key.equals (key)) { V old = E.value; E.value = value; return old; } } modcount++; if (count >= threshold) { //Rehash The table if the threshold is exceeded Rehash (); tab = table; Index = (hash & 0x7FFFFFFF)% Tab.length; } Creates the new entry. Entry e = Tab[index]; Tab[index] = new Entry (hash, key, value, e); count++; return null; }
The Put method of HashMap is as follows:
Public V put (K key, V value) { if (key = = null) return Putfornullkey (value); int hash = hash (Key.hashcode ()); int i = indexfor (hash, table.length); for (Entry e = table[i]; E! = null; e = e.next) { Object k; if (E.hash = = Hash && (k = e.key) = = Key | | key.equals (k))) { V oldValue = e.value; E.value = value; E.recordaccess (this); return oldValue; } } modcount++; AddEntry (hash, key, value, I);
By comparison with the put method of Hashtable and HashMap, it is easy to draw the conclusion that:
A, Hashtable put method is synchronous, thread-safe; The put method of HashMap is not synchronous, non-thread-safe: This shows that the Put method in Hashtable should be used in multithreaded situations, and the Put method in HashMap should be used instead. It can also be concluded that the put method of Hashtable is less efficient than the HashMap put method;
b, when put data to Hashtable, key and value cannot be null, and when put data to HashMap, both key and value can be null;
The difference between Hashtable and HashMap