Wechat search “Java fish”, a knowledge point every day not bad

(1) One knowledge point every day

How does HashMap work?

(2) Conclusions

(2.1) Features of HashMap

Underlying a HashMap is a hash table that stores values as an array plus a linked list. HashMap has the following characteristics:

1. A HashMap allows keys and values to be null

2.HashMap is thread unsafe

3. The initial capacity of the HashMap is 16 and the load factor is 0.75

4. In jdk7.0, the bottom layer is arrays plus linked lists; In jdk8.0, the bottom layer is array plus linked list plus red-black tree

(2.2) HasnMap PUT operation

HashMap maintains the Node type array table. When HashMap creates objects, set the load factor to 0.75 and table to null.

When adding elements for the first time, set the table size to 16 and threshold to 12

Call putVal each time you add an element:

1. Calculate the hash value of the key and the table capacity -1 to obtain the index value

2. Judge whether there are elements in the storage position, if there are no elements, put them directly; If an element already exists at that index location, continue to judge

3. If the element in this position is equal to the added element, it will be overwritten directly. If not, it will continue to judge whether it is a linked list structure or a tree structure, and add it in the corresponding way.

If the number is greater than the threshold, run resize to double the capacity. And rearrange them out of order.

(3) Learn a little more

HashMap, HashTable, TreeMap TreeMap TreeMap TreeMap TreeMap TreeMap TreeMap TreeMap TreeMap TreeMap TreeMap TreeMap TreeMap