The underlying implementation principle of HashMap

HashMap, a very commonly used collection, Key, Value format, which is the specific embodiment of the hash table

   There are three initialization methods, as follows:

    1,public HashMap(int initialCapacity, float loadFactor)

    2,public HashMap(int initialCapacity)

    3,public HashMap()

In the first initialization method, the first parameter is the initialization size, that is, the size of the array, the size of the array? What array size? Let's look at a piece of code first:

It can be inferred from the above code that HashMap is actually a "linked list hash" data structure, that is, a combination of an array and a linked list. The specific conversion diagram is:

Explain: The median value of the hash value array comes from the key in map.put(key, value). First, according to the key, the corresponding hash value is calculated. If the hash is the same, it is judged whether there is the same key in the subsequent linked list. If not, add a new value, otherwise directly overwrite the original value and return

Of course, if it is added, it is necessary to judge whether the length is greater than the initial size. If it is greater than the original length, it needs to be expanded to twice the original size, and then recalculate the position of the key in the linked list, recreate an Entry and point to the hash bucket index of the array Location

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324467093&siteId=291194637