table of Contents
HashMap is an object commonly used in JAVA. Its underlying realization principle is realized by the structure of array + linked list (PS: jdk 8 becomes an array + <linked list/red-black tree (the number of elements in the linked list is greater than 8 switch to a red-black tree) >)
1. Principle
Take the following simple diagram as an example. When a HashMap is created, an empty array will be created.
When using the put() method, that is, adding key-value elements in, the bottom layer is to get an integer from the key through the hashCode() method, which is used as the subscript of the array to store the element, but when the hashCode of the key is the same (that is, the hash collision) It will be added after the previous element at the same subscript position to form a linked list structure, and the previous existing element has a pointer to the next element.
When using the get() method to get an element, the bottom layer is to get the hashcode of the key, then locate the subscript through the code, and then use the equla() method to determine whether the key is equal to get the value of the element.
2. Expansion
When using new HashMap<, >(), the default expansion coefficient is 0.75, and the initial size is 16, which means that when the number of existing elements exceeds 12, it will automatically rehash. Perform a 2*16 (2n) expansion. The expansion operation is very performance-consuming, and the subscripts will be re-allocated.
Third, Hashcode
The HashCode of HashMap is a collection of hashes, in which the object can find a code of its own, which is specifically obtained through bit operations through the Java Hash algorithm. Different objects may get the same hashCode (collision)
Four, traversal method
HashMap<String,String> map=new HashMap<>();
Iterator it=map.entrySet().iterator();
while (it.hasNext()){
Map.Entry entry= (Map.Entry) it.next();
Object key=entry.getKey();
Object value=entry.getValue();
}
Five, JDK1.8
HashMap put() is replaced by the tail insertion method after JDK8. When the length of the linked list is greater than 8, the linked list will be converted into a red-black tree, and the query complexity will change from 0 (n) to 0 (Log n)
Six, summary
The implementation of Hashtable is basically the same as HashMap. The difference is in the way of hashcode generation and modulus, and the addition of synchronized to make a thread safe, so the performance is slightly lower.
PS: The thread is not safe. When hashMap expands data, it will reverse the position of the elements of the linked list . If two threads operate at the same time, two reversals will be formed, forming a loop lock state.
Array + linked list structure | Initial size | Expansion | Expansion factor | hashCode | Thread | key,value |
HashMap | 16 | 2n | 0.75 | Bit operation | Not safe | Can be empty |
HashTable | 11 | 2n + 1 | 0.75 | Modulo | Safety | Cannot be empty |