Let's first look at the definitions of the two classes.
Public class hashtable extends dictionary implements map, cloneable, java. Io. serializable
Public class hashmap extends actmap implements map, cloneable, serializable
It can be seen that hashtable inherits from dictiionary, while hashmap inherits from abstractmap.
The PUT Method of hashtable is as follows:
Public synchronized v put (K key, V value) {// ###### Note: 1 // make sure the value is not null if (value = NULL) {// ###### note here 2 throw new nullpointerexception ();} // makes sure the key is not already in the hashtable. entry tab [] = table; int hash = key. hashcode (); // ###### note here 3 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 ;}
Note: 1. The method is synchronous.
Note that value = NULL is not allowed in method 2.
Note 3: The hashcode method of key is called. If key = NULL, a null pointer exception is thrown. The PUT Method of hashmap is as follows:
Public v put (K key, V value) {// ###### note here 1 If (Key = NULL) // ####### note here 2 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); // ###### note that return NULL here ;}
NOTE 1: The method is not synchronous.
NOTE 2: Key = NULL is allowed.
Note that the 3 method does not call the value, so the value can be null.
Supplement:
Hashtable has a contains method, which may cause misunderstanding. Therefore, it has been removed from hashmap.
Of course, both classes use the containskey and containsvalue methods.
Conclusion:Ashmap is preferred in most cases.