Schematic set 4: HashMap, schematic set hashmap
First knowledge of HashMap
In the previous List, we talked about ArrayList and javaslist, and finally CopyOnWriteArrayList. In terms of the first two, we reflected two ideas:
(1) ArrayList is implemented in the form of an array. The insert and query operations are fast and the insert and delete operations are slow.
(2) The sort list is implemented in the form of a linked list. The sequence insertion and query are slow, and the insertion and deletion are convenient.
Is there a data structure that can combine the advantages of the above two types? Yes. The answer is HashMap.
HashMap is a very common, convenient and useful set, is a key-Value Pair (K-V) form of storage structure, the following will be the way to interpret the implementation principle of HashMap with diagrams,
Answers with four focuses on HashMap
| Close note |
Conclusion |
| Whether HashMap can be empty |
Both Key and Value can be empty. |
| Whether repeated data is allowed in HashMap |
Duplicate Key will overwrite, and repeated Value will be allowed |
| Whether HashMap is ordered |
Unordered. In particular, this unordered refersWhen traversing a HashMap, the order of the elements obtained is basically not the order of put. |
| Whether HashMap is thread-safe |
Non-thread security |
Add data
First, let's take a look at a HashMap storage unit Entry:
static class Entry
implements Map.Entry
{ final K key; V value; Entry
next; int hash; ...}
In the previous article about the sort list, the sort list is a two-way linked list. It can be seen from the Entry of HashMap that the Entry isUnidirectional linked listBecause there is only the next Entry of the Entry, but there is no front Entry of the Entry. The following figure shows a Data Structure:
Next, let's assume that I have the following code:
1 public static void main(String[] args)2 {3 Map
map = new HashMap
();4 map.put("111", "111");5 map.put("222", "222");6 }
Let's take a look at what we have done. First, starting from row 3rd, a new HashMap is created:
1 public HashMap() {2 this.loadFactor = DEFAULT_LOAD_FACTOR;3 threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);4 table = new Entry[DEFAULT_INITIAL_CAPACITY];5 init();6 }
Note that the init () of the first line is an empty method, which is used when constructing a HashMap subclass, such as LinkedHashMap. DEFAULT_INITIAL_CAPACITY is 16. That is to say, HashMap constructs a 16-size Entry array when it is new. All data in the Entry takes the default value, as shown in:
We can see that a new Entry array of 16 is generated. In the second row, put a string with the same Key and Value as 4th. Let's take a look at what the underlying layer did during put:
1 public V put(K key, V value) { 2 if (key == null) 3 return putForNullKey(value); 4 int hash = hash(key.hashCode()); 5 int i = indexFor(hash, table.length); 6 for (Entry
e = table[i]; e != null; e = e.next) { 7 Object k; 8 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { 9 V oldValue = e.value;10 e.value = value;11 e.recordAccess(this);12 return oldValue;13 }14 }15 16 modCount++;17 addEntry(hash, key, value, i);18 return null;19 }
1 static int hash(int h) {2 // This function ensures that hashCodes that differ only by3 // constant multiples at each bit position have a bounded4 // number of collisions (approximately 8 at default load factor).5 h ^= (h >>> 20) ^ (h >>> 12);6 return h ^ (h >>> 7) ^ (h >>> 4);7 }
1 static int indexFor(int h, int length) { 2 return h & (length-1); 3 }
Take a look at the steps of the put method:
1. 2nd rows ~ The reason why HashMap allows the Key value to be null is that the null Key is placed on the 3rd-Bit Array by default.
2. Obtain the HashCode of the Key value in Row 3. Since HashCode is the Object method, each Object has a HashCode, which is used for hash calculation. According to the JDK source code comment, this hash function is to disrupt a given HashCode to prevent bad Hash values generated by some bad Hash algorithms, as to why we should avoid bad Hash values, the last part of adding elements to HashMap will be discussed.
3. Based on the re-calculated HashCode of Row 3, modulo the size of the Entry array to obtain the position of an Entry array. As you can see, shift speeds up code execution. In addition, the correctness of this modulo operation depends on the length must be the N power of 2. This friend familiar with binary must understand, soNote: In the HashMap constructor, If you specify the size of the initial HashMap array initialCapacity, and initialCapacity is not the N power of 2, HashMap calculates the N power value greater than the minimum 2 power of initialCapacity, the initialization size of the Entry array.. For convenience, we assume that the I calculated by string 111 and string 222 is 1.
4. 6th rows ~ The 14th row first checks whether the same Key value exists in the original data structure, overwrites it, and returns it without executing the subsequent code. Note that the recordAccess method is also a subclass of HashMap, for example, used by LinkedHashMap. The HashMap method is empty. In addition, note that if the Key is the same, the system first checks whether the HashCode is the same and the HashCode is the same before determining whether equals is true. This greatly increases the efficiency of HashMap, if you are not familiar with HashCode, read this article and talk about the role of HashCode.
5. The modeCount ++ of rows 16th is used for the fail-fast mechanism. This value is automatically added every time the HashMap data structure is modified.
Then the key addEntry method is reached:
void addEntry(int hash, K key, V value, int bucketIndex) { Entry
e = table[bucketIndex]; table[bucketIndex] = new Entry
(hash, key, value, e); if (size++ >= threshold) resize(2 * table.length);}
Entry(int h, K k, V v, Entry
n) { value = v; next = n; key = k; hash = h;}
If the new Entry address is 0x00000001, put ("111", "111") is shown in the figure as follows:
Each newly added Entry is located on table [1]. In addition, the hash in it is the hash after rehash, rather than the original hash of the Key. We can see that the 111 --> 111 key-value pair is stored on table [1]. It holds the reference address of the original table [1], so it can be addressed to the original table [1], this is a one-way linked list. Let's take a look at what put ("222", "222") has done. A picture can be understood:
The new Entry occupies the position of table [1] Again, and holds the original table [1], that is, the 111 --> 111 key-value pair.
So far, the process of putting data in HashMap is clearly presented. But there is another problem, that is, how to resize HashMap. Let's look at the addEntry method again:
1 void addEntry(int hash, K key, V value, int bucketIndex) { 2 Entry
e = table[bucketIndex]; 3 table[bucketIndex] = new Entry
(hash, key, value, e); 4 if (size++ >= threshold) 5 resize(2 * table.length); 6 }
See the 4th rows ~ The number of rows is 5th. That is to say, after each Entry is placed, the system determines whether to expand the capacity. The reason for resizing is thatImproper use of HashMap expansion will lead to an endless loopThis is a topic worth exploring and a problem I encountered in my work. Therefore, the next article will explain in detail why improper use of HashMap leads to an endless loop.
Delete data
There is a piece of code:
1 public static void main(String[] args)2 {3 Map
map = new HashMap
();4 map.put("111", "111");5 map.put("222", "222");6 map.remove("111");7 }
Delete the element in Row 3. Let's see what we did when deleting the element. Line 3 ~ If two key-value pairs are added to row 5th, the above figure will be followed. The source code for deleting a key-Value Pair in HashMap is:
1 public V remove(Object key) { 2 Entry
e = removeEntryForKey(key); 3 return (e == null ? null : e.value); 4 }
1 final Entry
removeEntryForKey(Object key) { 2 int hash = (key == null) ? 0 : hash(key.hashCode()); 3 int i = indexFor(hash, table.length); 4 Entry
prev = table[i]; 5 Entry
e = prev; 6 7 while (e != null) { 8 Entry
next = e.next; 9 Object k;10 if (e.hash == hash &&11 ((k = e.key) == key || (key != null && key.equals(k)))) {12 modCount++;13 size--;14 if (prev == e)15 table[i] = next;16 else17 prev.next = next;18 e.recordRemoval(this);19 return e;20 }21 prev = e;22 e = next;23 }24 25 return e;26 }
Several steps are taken to analyze the remove element:
1. Locate the location of the key-value pair to be deleted based on the key hash.
2. record a prev to indicate the previous position of the Entry to be deleted, and e can be considered as the current position.
3. Starting from table [I], if a matched Entry is found, check whether the Entry is table [I]:
(1) Yes, that is, the 14th rows ~ In row 3, table [I] is directly the next node of table [I ].
(2) If it is not, it is 16th rows ~ In row 17th, the first Entry of e is prev. The next of prev points to the next node of e, that is, next. In this way, the Entry represented by e is kicked out, e's front and back entries are connected.
Remove ("111") is shown in the figure:
You only need to modify the next value of a node during the entire process, which is very convenient.
Modify data
The modified element is also put. Let's take a look at the source code:
1 public V put(K key, V value) { 2 if (key == null) 3 return putForNullKey(value); 4 int hash = hash(key.hashCode()); 5 int i = indexFor(hash, table.length); 6 for (Entry
e = table[i]; e != null; e = e.next) { 7 Object k; 8 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { 9 V oldValue = e.value;10 e.value = value;11 e.recordAccess(this);12 return oldValue;13 }14 }15 modCount++;16 addEntry(hash, key, value, i);17 return null;18 }
As mentioned above, there are 6th rows ~ Row 3 is the logic for modifying elements. If a Key already exists in the data structure, it overwrites the original value, that is, the code of Row 3.
Insert data
The so-called "insert element" must be based on the data structureOrdered. For example, ArrayList and history list are databases. One row is ordered.
HashMap is based on HashCode. HashCode is a random number, so entries in HashMap are stored randomly. HashMap does not maintain the sequence of inserted elements like LinkedHashMap. Therefore, it is meaningless to insert elements to the HashMap data structure.
Therefore, HashMap does not have the concept of insert.
The importance of HashCode
As mentioned above, the HashCode of the Key in HashMap should be rehash once to prevent bad HashCode generated by some bad Hash algorithms. Why should we prevent bad HashCode?
A bad HashCode means a Hash conflict, that is, multiple different keys may obtain the same HashCode.The bad Hash algorithm means that the probability of Hash conflicts increases, which means that the performance of HashMap will decrease in two aspects:
1. There are 10 keys. The HashCode of six keys may be the same. The entries of the other four keys are evenly distributed in the table, A location is connected with six entries. This loses the meaning of HashMap. The premise of structural high performance of HashMap data is that,Entries are evenly distributed on the table.But now it is the distribution of 1 1 1 6. So,We require that HashCode be random.To ensure the random Entry distribution and improve the HashMap efficiency.
2. Code for HashMap to traverse a table at a certain table location:
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
As we can see, because the "&" operator is used, we can compare HashCode first. If HashCode is not the same, we can directly pass it. equals will not be compared. Because HashCode is an int value, it is very fast, and the equals method often compares a series of content, the speed will be slower.The probability of Hash conflicts is high, which means that the number of equals comparisons is bound to increase.It will inevitably reduce the efficiency of HashMap.
Why is the table of HashMap transient?
A very detailed point:
transient Entry[] table;
We can see that the table is modified with transient. That is to say, all the content in the table will not be serialized. I wonder if you have thought about the reason for this writing?
In my opinion, such writing is very necessary. Because HashMap is based on HashCode, as the Object method, HashCode is native:
public native int hashCode();
This means:HashCode is related to the underlying implementation. Different virtual machines may have different HashCode algorithms.. Further, we can understand that the HashCode of the same Key on Virtual Machine A may be 1, The HashCode on Virtual Machine B is 2, and the HashCode on Virtual Machine C is 3.
This is a problem. Since its birth, Java has made cross-platform as the biggest selling point. Well, if the table is not modified by transient, programs that can be used on Virtual Machine A and those that can be used on Virtual Machine B are no longer available, because:
1. Key HashCode = 100 on vm a, connected to table [4]
2. Key HashCode = 101 on vm B. In this way, go to table [5] to find the Key, which is obviously not found.
The entire code goes wrong. To avoid this, Java adopts the method of rewriting its own serialized table. In writeObject, append the key and value to the end of the serialized file:
private void writeObject(java.io.ObjectOutputStream s) throws IOException{Iterator
> i = (size > 0) ? entrySet0().iterator() : null;// Write out the threshold, loadfactor, and any hidden stuffs.defaultWriteObject();// Write out number of bucketss.writeInt(table.length);// Write out size (number of Mappings)s.writeInt(size); // Write out keys and values (alternating)if (i != null) { while (i.hasNext()) { Map.Entry
e = i.next(); s.writeObject(e.getKey()); s.writeObject(e.getValue()); } }}
In readObject mode, the HashMap data structure is reconstructed:
Private void readObject (java. io. objectInputStream s) throws IOException, ClassNotFoundException {// Read in the threshold, loadfactor, and any hidden stuffs. defaultReadObject (); // Read in number of buckets and allocate the bucket array; int numBuckets = s. readInt (); table = new Entry [numBuckets]; init (); // Give subclass a chance to do its thing. // Read in size (number of Mappings) int size = s. readInt (); // Read the keys and values, and put the mappings in the HashMapfor (int I = 0; I
It is a troublesome method, but it ensures cross-platform performance.
This example also tells us that although most of the virtual machines used are HotSpot, it cannot be ignored by other virtual machines. It is a good thing to have a cross-platform idea.
Differences between HashMap and Hashtable
HashMap and Hashtable are similar key-value pairs. Their differences are also one of the frequently asked questions during interviews. Here I will briefly summarize the differences between HashMap and Hashtable:
1. Hashtable is thread-safe. All methods provided by Hashtable use synchronized, that is, synchronization, while HashMap is thread-safe.
2. Hashtable does not allow empty values. Empty values will lead to NULL pointer exceptions, while HashMap does not matter. There is no such restriction.
3. The above two shortcomings are the main differences. The other difference is irrelevant. I just mention that the two rehash algorithms are different. What Hashtable does:
private int hash(Object k) { // hashSeed will be zero if alternative hashing is disabled. return hashSeed ^ k.hashCode();}
This hashSeed is generated using the randomHashSeed method of the sun. misc. Hashing class. The rehash algorithm of HashMap has been read above, that is:
static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4);}