HashMap Source Code Reading Notes-implementation Principle Analysis of HashMap, hashmap source code
Before the release of Java 8, the implementation of HashMap is simply a Node array. The hash algorithm is used to distribute the positions of elements as much as possible. When a position has more than one element, connect elements in the form of a linked list. In Java 8, the implementation form of HashMap has been changed. The more important one is the linked list threshold. when the length of the linked list is greater than or equal to 7, converts the linked list at this position into a red/black tree, for example.
Let's talk about the hash algorithm. The algorithm used in HashMap is as follows:
Static final int hash (Object key) {int h; return (key = null )? 0: (h = key. hashCode () ^ (h >>> 16 );}
This hash first shifts the key to the right by 16 bits, and then performs the XOR operation with the key. Here, another & operation in the put method is involved,
Tab is a table, n is the size of the map set, and hash is the return value of the preceding method. Because we usually do not specify the size when declaring a map set, or create a map object with a large size during initialization, therefore, the hash algorithm based on the capacity size and key value will only calculate the low position at the beginning, although the two-step capacity is 0 at the beginning, however, the key's Two-Step high bit usually has a value. Therefore, in the hash method, first shift the hashCode of the key to the right 16 bits in the same or as itself, so that the key's high position can also be used in the hash, this reduces the collision rate to a greater extent.