How to analyze the HashMap source code
This article will explain in detail how to carry out HashMap source code analysis, the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
The code is based on JDK 1.8
Cardinal knowledge
Map is a data collection interface that holds Key-Value key-value pairs. HashMap is a Map implementation based on HashCode. Because HashCode is based on Key for storage, Key is unique in HashMap.
All Key,Value in HashMap can be null.
Source code parsing class declaration 1
two
three
Public class HashMap extends AbstractMap implements Map, Cloneable, Serializable {
/ /...
}
Map-AbstractMap itself implements the Map interface, and here it is emphasized again that HashMap implements Map
Cloneable implements the clone interface.
Serializable implements the serialization interface
Data structure 1
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
/ * *
* table is initialized when it is used for the first time and resized if necessary.
* when allocating size, the length is always a power of 2
, /
Transient Node [] table
/ / Node static inner class, linked list data structure
Static class Node implements Map.Entry {
Final int hash
Final K key
V value
Node next
Node (int hash, K key, V value, Node next) {
This.hash = hash
This.key = key
This.value = value
This.next = next
}
}
The above code describes the underlying data structure of HashMap: array + linked list.
In 1.8, red and black trees were added, with detailed study.
Constructor function
For constructors, several overloads are provided to facilitate the creation of instances:
one
two
three
four
Public HashMap ()
Public HashMap (int initialCapacity)
Public HashMap (int initialCapacity, float loadFactor)
Public HashMap (Map