First recognition HashMap
Based on the implementation of the map interface of a hash table (that is, a hash table), this implementation provides all the optional mapping operations and allows NULL values and NULL keys to be used.
HashMap inherits from Abstractmap, and realizes the map, cloneable, java.io.Serializable interface. and is not synchronized, meaning it is not thread-safe.
Data structure of HashMap
In the Java programming language, the most basic structure is two, one is an array, the other is an analog pointer (reference), all the data structures can be constructed with these two basic structures. HashMap is no exception, it is an "array of linked lists" data structure. It can be seen from the bottom of hashmap is a table array, the elements of the array is entry. and entry is a storage unit in the HashMap.
Data structure of entry
Each element in the table array is a one-way list made up of entry, which is important to understand HashMap.
Now look at the data structure of a entry on one-way linked list and the definition of its source code.
1 Static class Implements Map.entry<k,v> {2 final K key; 3 V value; 4 Entry<k,v> Next; 5 Final int Hash;
HashMap Access implementation 1, storage data
First, from the code I wrote to start, open the HashMap source parsing path:
1 Public Static void Main (string[] args) 2 {3 new hashmap<string,string>(); 4 Hashmap.put ("Language", "the"); 5 Hashmap.put ("Mathematics", "the"); 6 Hashmap.put ("English", "the"); 7 }
In line 3rd, a hashmap is created.
1 Public HashMap () {2 this. loadfactor = default_load_factor; 3 Threshold = (int) (default_initial_capacity * default_load_factor); 4 New entry[default_initial_capacity]; 5 init (); 6 }
Where the initial capacity default_initial_capacity is 16,loadfactor (load factor) is 0.75. That is to say, HashMap constructs a entry array of size 16 at the time of creation. All data in the entry takes the default value of NULL.
Next look at how the Put method is implemented at the bottom:
1 Publicv put (K key, V value) {2 if(Key = =NULL)3 returnPutfornullkey (value);4 inthash =Hash (Key.hashcode ());5 inti =indexfor (hash, table.length);6 for(entry<k,v> e = table[i]; E! =NULL; E =e.next) {7 Object K;8 if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) {9V OldValue =E.value;TenE.value =value; OneE.recordaccess ( This); A returnOldValue; - } - } the -modcount++; - addentry (hash, key, value, I); - return NULL; +}
1, on the 2, 32 lines, you can see that HashMap allows the existence of a key value of NULL, and stored in the location of the data is 0.
2.
In-depth understanding of the Java Collection series: HashMap Source code interpretation