Talking about HashMap

1. The underlying principle of HashMap (based on jdk8)?

The essence of HashMap is based on arrays and linked lists. It takes full advantage of the fast array query and the fast addition and deletion of linked lists. Just like linked lists, just change the pointer. The array stores each
Node object, and the Node node includes hash, key, value, and next. Determine the subscript of the Node stored in the array through the hash value of the key. The hash value is obtained
through displacement and XOR through the hashCode() method of the key . The purpose is to reduce the hash collision, and then through the hash value and the capacity of the HashMap- 1 Perform & operation to get the array subscript. Previously, it
was obtained by% operation. This is why the capacity of HashMap is 2 to the nth power. If the array element is empty, insert it directly. If it is not empty
, compare it according to the hash value of the key and the equals() method. This is also the reason why the HashMap query is fast. If it is different, it is placed in the linked list. If the length of the linked list is greater than 8, it may be converted to Red-black tree.

/**
 * 通过key的hashCode()值进行位移和异或运算,降低哈希碰撞
 */
static final int hash(){
	int h;
	return (key==null)? 0:	(h=key.hashCode())^(h>>>16);
}

2. What is the difference and connection between hashCode() and equals() in Object? What should I pay attention to when the Key of HashMap is a reference type?

hashCode() maps the address, field and other information of the object into an int type hash value according to certain rules. equals () is to compare the address of the object, if the object is to
address the same, then hashCode () value must equal the value of hashCode () is not equal, then the two objects must not want to wait, this is the put and get HashMap will First judge whether the hash
values ​​are equal and then compare the reason with equals().
The equals() and hashCode() methods will be rewritten, because the search is based on whether the hash value of the key and the address are equal to determine whether it is the same element. If you don’t rewrite it,
you should get a null.

3. What is a hash collision?

A phenomenon in which different objects generate the same hash value through a hash function.

4. Why is the length of HashMap 2 to the power of n? What are the functions of shift operation and XOR operation in hash() function?

The value generated by hash() is exactly the same as the n-th power of 2 and the & operation to get the subscript of the array. The efficiency of & operation is higher than% operation.
The displacement operation and XOR operation in the hash() function are to reduce hash collisions and avoid storing in the same array subscript of HahsMap.

5. How to implement the put method and capacity expansion of HashMap?

put()
1. Determine whether the HashMap is empty or whether the length is 0, which is to initialize the expansion.
2. Determine the array subscript according to the hash value of the key. If the corresponding value is null, insert the object directly, otherwise compare whether the key exists (by hash() value and address), and there is an overwrite.
3. If it does not exist, determine whether it is a red-black number or a linked list. The red-black tree is directly inserted, and then the red-black tree is balanced. If it is a linked list, the linked list is traversed, and there is coverage, but there is no insertion. The
length of the linked list is greater than 8 and converted to Red-black tree.
4. When size is greater than the capacity load factor 0.75, expand the capacity.
resize()
1. When the length of the HashMap is 0, initialize it, and the default capacity is 16.
2. When the length of the HashMap is greater than the capacity
load factor of 0.75, the capacity is expanded, and the length of the array after expansion is twice the original, and the elements are either at the current position or at the position after the current subscript is doubled.
Insert picture description here

/**
 * jdk1.8HashMap中的put方法
 */
 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)     /*第一次扩容*/
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))      /*判断key是否存在*/
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();   /*第二次扩容*/
        afterNodeInsertion(evict);
        return null;
    }

6. What is the difference between Java7 and Java8 HashMap?

1. Array + Linked List ------> Array + Linked List + Red-Black Tree
2. The value of hash() 9 perturbations ------> 2 perturbations Displacement and XOR operation
3. Head interpolation- ----->Unplugging method to avoid dead link

7. What is the difference between HashMap and HashTable?

1. HashTable is decorated with Synchronized and is thread-safe. HashMap is non-thread-safe, so the efficiency will be higher than HashTable.
2. The key of HashTable cannot be null, and the key of HashMap can be null.

8. Why is HashMap thread unsafe?

The put method will lead to data overwriting. Assuming that A and B are two threads, A thread is executed to determine whether there is a code time segment of key, B thread inserts the same key,
A will overwrite the value of B, and thread insecurity occurs.

9.ConcurrentHashMap?

Resolve after learning concurrency related knowledge, to be continued...

Guess you like

Origin blog.csdn.net/shiquan202101/article/details/111751384