HashMap is a HashMap that Java can’t get around, but what is the difference between HashMap and HashTable?
1.HashMap is not synchronized whereas HashTable is synchronized
So if you’re not dealing with multithreaded concurrency, you’re using HashMap, but if you’re dealing with multithreaded concurrency, you’re using HashTable? Unfortunately, this is not the case. Instead of using HashMap, use ConcurrentHashMap.
2.HashMap allows one null key or multiple NULL values
HashTable does not allow null keys or values, and ConcurrentHashMap does not allow null keys or values.
3.HashTable is a legacy class
HashTable was introduced in JDK1.0 and HashMap was introduced in JDK1.2.
4.HashTable is slower than HashMap
Since HashTable adds synchronization to all major methods,
public synchronized V get(Object key)
So HashTable is slower to access than HashMap.
5. When a HashMap iterative modifications will throw ConncurrentModificationException
In the HashMap iteration and modify a HashMap, will be thrown ConncurrentModificationException
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0&& (tab = table) ! =null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for(Node<K,V> e = tab[i]; e ! =null; e = e.next)
action.accept(e);
}
if(modCount ! = mc)throw newConcurrentModificationException(); }}Copy the code