Don't understand HashMap? Just because you lack a HashMap flowchart!

Many people don't understand HashMap, I think the reason is that their learning method is wrong! Today I summarized a process of the put method of HashMap and shared it with you!

During the interview, HashMap is basically a must-have knowledge point.

When many people answer, they follow the script. HashMap stores data according to the hashCode value of the key. In most cases, its value can be located directly, so it has a fast access speed, but the traversal order is uncertain. HashMap only allows the key of one record to be null at most, and allows the value of multiple records to be null. HashMap is not thread safe, that is, multiple threads can write HashMap at the same time, which may cause data inconsistency. If you need to meet thread safety, you can use the synchronizedMap method of Collections to make HashMap thread-safe, or use ConcurrentHashMap.

I can tell at a glance that he did his homework before the interview. I don't really understand HashMap, a put method will bring him back to its original shape!

Why do people who study well study well? Because others are good at summarizing! Okay, don't talk nonsense, look at my picture!

Don't understand HashMap?  Just because you lack a HashMap flowchart!

Simply put, you can summarize it in the following few sentences!

①. Determine whether the key-value pair array table[i] is empty or null, otherwise execute resize() to expand;

②. Calculate the hash value according to the key value key to get the inserted array index i, if table[i]==null, directly create a new node to add, go to ⑥, if table[i] is not empty, go to ③;

③. Determine whether the first element of table[i] is the same as key, if the same, directly overwrite value, otherwise go to ④, where the same refers to hashCode and equals;

④. Determine whether table[i] is a treeNode, that is, whether table[i] is a red-black tree, if it is a red-black tree, insert the key-value pair directly into the tree, otherwise go to ⑤;

⑤. Traverse table[i], determine whether the length of the linked list is greater than 8, if it is greater than 8, convert the linked list to a red-black tree, and perform the insertion operation in the red-black tree, otherwise perform the insertion operation of the linked list; if the key already exists during the traversal process Just overwrite value directly;

⑥. After the insertion is successful, judge whether the actual number of key-value pairs size exceeds the maximum capacity threshold, and if it exceeds, expand the capacity.

Similarly, when you draw a flowchart of other methods of HashMap, you will find that everything is so simple!

Guess you like

Origin blog.51cto.com/15127565/2668874