In-depth understanding of HashMap and source code, HashMap interview questions

One, HashMap

  1. HashMap is based on the principle of hashing, storing and obtaining objects through put() and get() methods. When we pass the key-value pair to put(), it will call the hashCode() method of the key object to calculate the hashCode corresponding to the key, and then find the corresponding bucket location to store the value object. When obtaining the value object, find the correct key-value pair through the equal() method of the key object, and then return the value object. HashMap uses a linked list to solve the collision problem. When a collision occurs, the key-value pair object is stored in the next node of the linked list.
  2. When the hashCode of two different key-value pair objects is the same, they will be stored in the linked list at the same bucket position, and the corresponding key-value pair will be found in the linked list through the equal() method of the key object.

Second, the difference between HashMap and Hashtable

Both HashMap and Hashtable implement the Map interface
3. HashMap is non-synchronized, Hashtable is synchronized, it is thread-safe, multiple threads can share a Hashtable, HashMap can not (can be resolved synchronously).
4. It can accept null->null key pair values, but Hashtable cannot. Java5 provides ConcurrentHashMap instead of Hashtable, which has better scalability than Hashtable.
5. HashMap cannot guarantee that the order of elements in the Map will not change over time.
6. The iterator of HashMap is a fail-fast iterator. When other threads modify the HashMap structure (add or remove elements), an exception will be thrown, but the collection object can be modified through the set() method. The remove() of the iterator itself Method to remove elements is also possible; Hashtable's iterator (enumerator) is not fast-fail.
7. sychronized means that only one thread can change the Hashtable at a time . That is to say, when any thread wants to update the Hashtable, it must first obtain the synchronization lock , and other threads must wait until the synchronization lock is released before obtaining the synchronization lock again to update the Hashtable.
8. HashMap synchronization method:Map m = Collections.synchronizeMap(hashMap);

Three, the difference between HashMap and HashSet

Guess you like

Origin blog.csdn.net/Cxf2018/article/details/109328235