1: The parent class is different

  • Hashtable

class Hashtable<K,V> extends Dictionary<K,V>

  • HashMap

HashMap<K, V> extends AbstractMap<K, V>

2: Capacity is different

  • Hashtable

This (11, 0.75 f);

  • HashMap

A HashMap (16, 0.75 f);

3: Thread safety is different

  • A HashMap: no lock
  • Hashtable: Lots of locks

4: a null value

  • HashMap: NULL can be used as a key (placed in the 0th position of the hash bucket)
  • HashTable: Neither key nor value is allowed to be null. Otherwise, NullPointerException will be thrown

5: Traversal mode:

  • HashMap : Iterator
  • HashTable: Enumeration** (/ I,nju:mə’reiʃən/ : count; List) * *

6: Hash values are used differently

  • HashMap: has its own hash function that recalculates its own hash value
  • HashTable: Uses the hashCode of the object directly
  • Ps: Here’s how a hashMap computes a hash
  /** * the perturbation function,  * Computes key.hashCode() and spreads (XORs) higher bits of hash * to lower. Because the table uses power-of-two masking, sets of * hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys * holding consecutive whole numbers in small tables.) So we * apply a transform that spreads the impact of higher bits * downward. There is a tradeoff between speed, utility, and * quality of bit-spreading. Because many common sets of hashes * are already reasonably distributed (so don't benefit from * spreading), and because we use trees to handle large sets of * collisions in bins, we just XOR some shifted bits in the * cheapest possible way to reduce systematic lossage, as well as * to incorporate impact of the highest bits that would otherwise * never be used in index calculations Because of the table bounds. * * Allows the top 16 bits of the key to address the route while the table size is too large. * /
    static final int hash(Object key) {
        int h;
        // key is empty and placed directly at 0;
        /* * h = 0b 0010 0101 1010 1100 0011 1111 0010 1110 * 0b 0010 0101 1010 1100 0011 1111 0010 1110 >>>16 = 0b 0000 0000 0000 0000 0010 0101 1010 1100 * * * 0b 0010 0101 1010 1100 0011 1111 0010 1110 * ^ * 0b 0000 0000 0000 0000 0010 0101 1010 1100 * * Xor result: * 0b 0010 0101 1010 1100 0001 1010 1000 0010 */
        return (key == null)?0 : (h = key.hashCode()) ^ (h >>> 16);
    }
Copy the code

7: The capacity expansion method is different

  • HashTable: old * 2 + 1
  • HashMap: 2 increased exponentially

What is the difference between a HashMap and a HashTable?