JAVA intermediate / collection framework - other collections - JAVA HASHMAP

Posted by a94060 on Sun, 16 Jan 2022 17:32:30 +0100

Collection framework Series Textbook (8) - other collections - Java HashMap

1. Key value pairs of HashMap

HashMap stores data in key value pairs

package collection;
   
import java.util.HashMap;
   
public class TestCollection {
    public static void main(String[] args) {
        HashMap<String,String> dictionary = new HashMap<>();
        dictionary.put("adc", "Physical hero");
        dictionary.put("apc", "Magic hero");
        dictionary.put("t", "Tank");
         
        System.out.println(dictionary.get("t"));
    }
}

2. The key cannot be repeated, and the value can be repeated

For HashMap, key s are unique and cannot be repeated.
Therefore, inserting different values into the map with the same key will cause the old elements to be overwritten, leaving only the last inserted element. However, the same object can be inserted into the map as a value, as long as the corresponding key is different.

3. Data structure of HashMap

Map overview (I): understand HashMap completely

1. Related concepts of hash

Hash is to transform any length of input (also known as pre image) into a fixed length output (usually integer) through hash algorithm, and the output is the hash value. This transformation is a compression mapping, that is, the space of hash value is usually much smaller than the input space. Different inputs may be hashed into the same output, so it is impossible to uniquely determine the input value from the hash value. In short, it is an information digest function that compresses messages of any length to a fixed length.

2. Application of hash: data structure

We know that the characteristics of arrays are: easy addressing, difficult insertion and deletion; The characteristics of the linked list are: difficult addressing, easy insertion and deletion. So can we combine the characteristics of the two and make a data structure that is easy to address and easy to insert and delete? The answer is yes. This is the hash table we want to mention. In fact, there are many different ways to implement hash tables. What we will explain next is the most classic method - zipper method, which can be understood as an array of {linked lists.

        HashMap of Java collection

In the java programming language, there are two basic structures, one is array and the other is analog pointer (Reference). All data structures can be constructed with these two basic structures, and HashMap is no exception. HashMap is actually a data structure of "array of linked list". Each element stores the array of chain header nodes, that is, the combination of array and linked list.

As can be seen from the above figure, the bottom layer of HashMap is an array structure, and each item in the array is a linked list. When a HashMap is created, an array will be initialized.

The bottom layer of HashMap is mainly based on arrays and linked lists. The reason why it has a very fast query speed is that it determines the storage location by calculating the hash code. HashMap mainly calculates the hash value through the hashCode of the key. As long as the hashcodes are the same, the calculated hash value is the same. If there are many stored objects, the hash values calculated by different objects may be the same, which leads to the so-called hash conflict. Students who have studied data structures know that there are many ways to solve hash conflicts. The bottom layer of HashMap solves hash conflicts through linked lists.

 4. Fast access principle of HashMap

Principle of HashMap for fast access

// Add "key value" to HashMap  
public V put(K key, V value) {  
    // If "key is null", add the key value pair to table[0].  
    if (key == null)  
        return putForNullKey(value);  
    // If "key is not null", calculate the hash value of the key, and then add it to the linked list corresponding to the hash value.  
    int hash = hash(key.hashCode());   // Calculate the position of key hash value in table array ------------ (1)
    int i = indexFor(hash, table.length);  // Iteration e, starting from i, find the location where the key is saved ------------ (2)
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {  
        Object k;  
        // If the key value pair corresponding to "this key" already exists, replace the old value with the new value. Then exit!  
        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 key value pair corresponding to "this key" does not exist, add "key value" to the table  
    modCount++;
    //Add key value to table[i]
    addEntry(hash, key, value, i);  
    return null;  
}

Through the source code, we can clearly see the process of HashMap saving data: first, judge whether the key is null. If it is null, directly call the putForNullKey method. If it is not empty, first calculate the hash value of the key, and then search the index position in the table array according to the hash value. If the table array has elements at this position, compare whether the same key exists. If it exists, overwrite the value of the original key. Otherwise, save the element at the head of the chain (the first saved element is placed at the end of the chain). If there is no element in the table, it will be saved directly.

HashMap principle reading

HashMap principle reading

Topics: Java