1: inheritance relationship
A: Hashtable inherits from the Dictionary class to implement the map and cloneable interfaces.
B: HashMap inherits from the AbstractMap class to implement the map and cloneable interfaces.
HashTable:
public class Hashtable
extends Dictionary
implements Map
, Cloneable, java.io.Serializable
HashMap:
public class HashMap
extends AbstractMap
implements Map
, Cloneable, Serializable
2: line program security considerations
A: HashTable is thread-safe.
B: hashmap is thread-safe.
HashMap is a lightweight Implementation of Hashtable (non-thread-safe implementation ).
3: can it be null?
2. HashTable does not allow null values (neither key nor value). HashMap allows null values (both key and value ).
Code:
HashTable does not allow null value
public synchronized V put(K key, V value) {// Make sure the value is not nullif (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; }
HashMap: the key runs as NULL.
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); return null; }