Analyze its hash storage mechanism by analyzing HashMap and HashSet source code
For HashSet, the system uses the hash algorithm to determine the storage location of the set elements, so that the set elements can be saved and taken quickly.
For HashMap, the system key-value as a whole, the system always calculates the storage location of Key-value according to the hash algorithm, so that the key-value of the map can be saved and taken quickly.
Although the collection is supposed to store Java objects, it does not actually put the Java objects in the Set collection, only the references to those objects are kept in the set collection.
That is, the Java collection is actually a collection of multiple reference variables that point to the actual Java object.
Storage implementation of HashMap
hashmap<string, double> map = new hashmap<string, double> (); Map.put ("language", 80.0); Map.put ("mathematics", 89.0); Map.put ("English", 78.2);
HashMap uses a so-called "hash Algorithm" to determine where each element is stored.
When the program executes Map.put ("language", 80.0), the system will invoke the "language" Hashcode () method to get its hashcode value ———— each Java object has a hashcode () method, which can be used to obtain its hashcode value.
After you get the Hashcode value for this object, the system determines where the element is stored, based on the hashcode value.
Public V put (K key, V value) {//If key is null, call the Putfornullkey method to process if (key = = null) return Putfornullkey (value); Computes the hash value int hash = hash (Key.hashcode ()) according to the keycode of key; Search for the index of the specified hash value in the corresponding table <strong> int i = indexfor (hash, table.length);</strong>//If I cable The Entry at the lead is not NULL, iterating through the next element of the E element for (entry<k,v> e = table[i]; e = null; e = e.next) { Object K; Locate the specified key equal to the key that needs to be placed (the hash value is the same//put back true by equals) if (E.hash = = Hash && (k = E.key) = = Key | | Key.equals (k))) {V oldValue = E.value; E.value = value; E.recordaccess (this); return oldValue; }}//If the Entry at index i is null, indicating there is no Entry modcount++; Add key, value toI at index addentry (hash, key, value, I); return null; }
The above program used to Map.entry, each map.entry is actually a key-value pair.
As can be seen from the above program: when the system decides to store the Key-value pair in the HashMap, it does not take into account the value in entry, but only calculates and determines the storage location of each entry based on key.
This also shows that the value in the Map collection is completely attached to the key, and when the system determines where the key is stored, value is stored there.
The above method provides a hashcode () return value to calculate the hash code method: hash (), this method is a purely mathematical calculation, the method is as follows:
static int hash (int h) { h ^= (H >>> a) ^ (h >>> N); Return h ^ (H >>> 7) ^ (H >>> 4); }
For any given object, the hash code value computed by the program call hash (int h) method is always the same as long as its hashcode () return value is the same.
The program then calls the indexfor (int h, int length) method to calculate at which index the object should be stored in the table array.
static int indexfor (int h, int length) { return H & (length-1); }
This method always uses H & (TABLE.LENGTH-1) to get the object's save location
The hashmap of the underlying array is always 2 of the n-th square.
When length is always a multiple of 2, H & (Length-1) will be a very ingenious design:
Assuming h=5, length = 16, then H & (Length-1) will get 5;
H=6,length=16, then h& (length-1) will get 6 .... H=15,length=16, then h& (length-1) will get 15;
But when h=16,length=16, then h& (length-1) will get 0;
When h=17,length=16, then H&length-1 will get 1
This ensures that the computed index value is always within the index of the table array.
When the program tries to put a key-value pair into HashMap, the program first determines the storage location of the entry based on the Hashcode () return value of the key:
If the hashcode () return values of the two entry keys are the same, they are stored in the same location.
If these two entry keys return True by equals, the newly added entry value overrides the entry value in the collection, but the key is not overwritten.
If these two entry keys return false by Equals, the newly added entry will form a entry chain with entry in the collection, and the newly added entry is located in the head of the entry chain.
When adding key-value pairs to HashMap, the hashcode () return value of its key determines where the key-value pair (that is, the entry object) is stored.
When the hashcode () return value of the key for the two entry object is the same, the key is determined by the Equals () comparison value to take the overwrite behavior (return true) or to produce a entry chain (return false).
The above program also calls the AddEntry (hash, key, value, I); code, where AddEntry is a method that HashMap provides a package access, which is used only to add a key-value pair.
void AddEntry (int hash, K key, V value, int bucketindex) { //Get Entry entry<k,v> e = at the specified Bucketindex index Table[bucketindex]; ① //Add the newly created Entry to the Bucketindex index and let the new Entry point to the original Entry Table[bucketindex] = new entry<k,v> (hash, key, Value, e); If the number of key-value pairs in the Map exceeds the limit if (size++ >= threshold) //extends the length of the table object to twice times. Resize (2 * table.length); ② }
The code for the above method contains a very elegant design: The system always places the newly added entry object into the Bucketindex index of the table array ————
If a entry object is already in place at the Bucketindex index, the newly added entry object points to the original entry object (producing a entry chain).
If there is no entry object at the Bucketindex index, that is, the e variable is null, that is, the newly placed entry object points to null, that is, the entry chain is not produced.
Performance options for hash algorithms
As can be seen from the above code, in the case of the same bucket storage entry chain, the new entry is always in the bucket, and the first place in the bucket entry is located at the end of the entry chain.
There are two more variables in the above program:
Size: The variable holds the number of key-value pairs contained in the HashMap.
Threshold: This variable contains the limit of the key-value pair that the HashMap can hold, and its value equals the capacity of HashMap multiplied by the load factor (load factor).
When size++ >= threshold, HashMap automatically calls the Resize method to expand the capacity of HashMap. For each expansion, the capacity of the hashmap is increased by one-fold.
The table array used is actually an ordinary array, each of which has a fixed length, and the length of the array is the capacity of the HashMap.
The HashMap contains the following constructors:
HashMap (): Build a HashMap with an initial capacity of 16 and a load factor of 0.75
HashMap (int initialcapacity): Build an initial capacity of initialcapacity with a load factor of 0.75 HashMap
HashMap (int initialcapacity, float loadfactor): Creates a HashMap with the specified initial capacity, specified load factor.
When creating a HashMap, the system automatically creates a table array to hold the entry in HashMap, and the following is the code for a constructor in HashMap:
Create HashMap public HashMap (int initialcapacity, float loadfactor) with the specified initialization capacity, load factor, {//initial capacity cannot be Negative if (Initialcapacity < 0) throw new illegalargumentexception ("illegal ini Tial capacity: "+ initialcapacity); If the initial capacity is greater than the maximum capacity, show capacity if (Initialcapacity > maximum_capacity) initialcapacity = Maximum_cap acity; The load factor must be greater than 0 if (loadfactor <= 0 | | Float.isnan (Loadfactor)) throw new IllegalArgumentException (Loadfactor); Calculates the minimum 2 N-square value that is greater than initialcapacity. int capacity = 1; while (capacity < initialcapacity) capacity <<= 1; This.loadfactor = Loadfactor; Set capacity limit equals capacity * load factor threshold = (int) (capacity * loadfactor); Initialize table Array table = new entry[capacity]; // ①init (); }
The code above contains a concise code implementation: Find the minimum 2 N-square value that is greater than initialcapacity, and use it as the actual capacity of the HashMap (saved by the capacity variable).
The essence of table is an array, an array of length capacity.
For HashMap and its subclasses, they use a hash algorithm to determine where the elements in the collection are stored.
When the system starts initializing HashMap, the system creates a entry array of length capacity, where the position of the element can be stored is called "bucket", each bucket has its specified index. The system can quickly access the elements stored in the bucket based on its index.
Whenever a bucket of HashMap stores only one element (that is, one entry), the entry object can contain a reference variable (that is, the last parameter of the entry constructor) to point to the next entry,
So what might happen is that there is only one entry in the HashMap bucket, but this entry points to another entry ———— which forms a entry chain.
Read implementation of HashMap
When the entry stored in each bucket of HashMap is only a single entry ———— that is, when the entry chain is not generated by the pointer, the HASHMAP at this time has the best performance:
When a program passes a key to the corresponding value, the system simply calculates the hashcode () return value of the key, finds the index of the key in the table array based on the Hashcode return value, and then takes out the entry at that index. Finally, the value corresponding to the key is returned.
Public V get (Object key) {//If key is null, call Getfornullkey to remove the corresponding value if (key = = null) return Getfornullkey (); Computes its hash code int hash = hash (Key.hashcode ()) According to the hashcode value of the key; Directly takes out the value at the specified index in the table array, for (entry<k,v> e = table[indexfor (hash, table.length)]; E! = null; Search the Entry chain for the next Entr e = e.next)//①{ Object K; If the Entry key is the same as the key being searched if (E.hash = = Hash && (k = e.key) = = key || Key.equals (k))) return e.value; } return null; }
As can be seen from the above code, if there is only one entry in each bucket of HashMap, HashMap can quickly take out the entry in the bucket according to the index;
In the case of a "hash conflict", a single bucket is not a entry, but a entry chain, and the system must only traverse each entry sequentially until it finds the entry it wants to search ————
If the entry that happens to be searched is at the very end of the entry chain (the entry is first placed in the bucket), the system must loop to the end to find the element.
HashMap at the bottom of the key-value as a whole to deal with, this whole is a entry object.
HashMap the bottom of a entry[] array to save all key-value pairs, when the need to store a entry object, according to the hash algorithm to determine its storage location;
When a entry needs to be taken out, it will also find its storage location according to the hash algorithm and take out the entry directly.
This shows: The reason why HashMap can quickly save and take the contained entry, exactly like a philosophy of life: different things to be placed in different locations, need to quickly find it
When creating HashMap, there is a default load factor (load factor) with a default value of 0.75, which is a tradeoff between time and space costs: increasing the load factor reduces the amount of memory space used by the hash table (that is, the entry array).
However, the time overhead of querying data is increased, and queries are the most frequent (HashMap get () and put () methods use queries);
Reducing the load factor increases the performance of the data query, but increases the amount of memory occupied by the hash table.
We can appropriately adjust the value of load factor when creating HashMap, if the program is concerned about the space overhead and the memory is more tense, the load factor can be increased appropriately.
If the program is more concerned about time overhead, the memory is relatively comfortable to reduce the load factor appropriately.
Typically, programmers do not need to change the value of the load factor.
If you know from the beginning that HashMap will save multiple key-value pairs, you can use a large initialization capacity at the time of creation, if the number of entry in HashMap never exceeds the limit capacity (capacity*load factor),
HashMap does not need to call the resize () method to reassign the table array, thus guaranteeing good performance. Of course, starting to set the initial capacity too high may waste space (the system needs to create a entry array of length capacity).
Therefore, it is also necessary to initialize the capacity settings when creating HashMap.
The realization of HashSet
For HashSet, it is based on the HashMap implementation, hashset the underlying hashmap to save all elements,
public class Hashset<e> extends abstractset<e> implements Set<e>, Cloneable, Java.io.s erializable {//Use HashMap key to save all elements in HashSet private transient hashmap<e,object> map; A virtual object object is defined as the value of the HashMap private static final Object PRESENT = new Object (); ...//Initialize HashSet, the underlying initializes a HASHMAP public HashSet () {map = new HASHMAP<E,OBJECT&G t; (); }//created with the specified initialcapacity, Loadfactor HashSet//is actually created with the corresponding parameters HashMap public HashSet (int initial capacity, float loadfactor) {map = new hashmap<e,object> (initialcapacity, loadfactor); } public HashSet (int initialcapacity) {map = new hashmap<e,object> (initialcapacity); } HashSet (int initialcapacity, float loadfactor, Boolean dummy) {map = new LINKEDHASHM ap<e,object> (INITialcapacity, Loadfactor); }//Call map KeySet to return all key public iterator<e> Iterator () {return Map.keyse T (). iterator (); }//Call HashMap the size () method returns the number of Entry, and the number of elements in the Set is given public int size () {return map . Size (); }//Call HashMap IsEmpty () to determine if the HashSet is empty,//When the HashMap is empty, the corresponding HashSet is also empty public boolean Isem Pty () {return map.isempty (); }//Call HashMap's containskey to determine if all elements that contain the specified key//hashset are saved by the key of the HashMap public boolean C Ontains (Object o) {return map.containskey (o); }//Put the specified element in HashSet, that is, put the element as a key HashMap public boolean Add (e) {return MAP.P UT (e, PRESENT) = = NULL; }//Call the HashMap Remove method to delete the specified Entry, and then delete the corresponding element in the HashSet public boolean remove (Object o) { RetUrn Map.Remove (o) ==present; }//The Clear method of calling Map clears all Entry, and clears all elements in HashSet public void Clear () {map.clear () ; } ... }
As can be seen from the source code, the implementation of HashSet just encapsulates a HashMap object to store all the collection elements,
All the collection elements placed in HashSet actually have HashMap key to save,
The value of HashMap stores a present, which is a static object.
Most of the methods of HashSet are implemented by invoking the HashMap method, so HashSet and HashMap two sets are essentially the same in their implementations.
HashMap's put and HashSet's add
Because the Add () method of HashSet adds the collection element, it actually turns to call HashMap's put () method to add the Key-value pair,
When the new entry in the HashMap key is the same as the entry key in the set (the Hashcode () return value is equal, and returns True by Equals, the newly added entry value overrides the original entry value, But key doesn't change anything,
So if you add an already existing element to the HashSet, the newly added collection element (the underlying is saved by the HashMap key) does not overwrite the existing collection element.
HashSet the criteria for determining the equality of two objects in addition to returning true through the Equals () method requires that the hashcode () return values of the two objects be equal.
So if the class only overrides the Equals () method without overriding the Hashcode () method, the Hashcode () return values of all two homogeneous objects with the same properties are different, so hashset will treat them as 2 objects.
It is important to override the Equals (Object obj) method and the Hashcode () method of the class when we try to treat the object of a class as a HashMap key, or try to save the object of that class into HashSet.
And the return values of the two methods must be consistent: when the hashcode () return values of the two objects of the class are identical, they should also return true through the Equals () method.
In general, all key attributes that participate in the calculation of the hashcode () return value should be used as the criteria for the Equals () comparison.
Java hashing mechanism