Implementation of the 1.HASHMAP
In JDK1.6, HashMap is implemented using an array + linked list, which uses a list to handle conflicts, and a linked list of the same hash value is stored in a list.
However, when there are more elements in a bucket, that is, when there are more elements with equal hash value, it is inefficient to search by key value, and the time complexity is O (n).
And a hash collision occurs when the node is added from the beginning, and the first list is stored at the end of the list.
JDK1.8, HashMap using array + linked list + red black tree implementation, when the list length exceeds the threshold (8), the linked list into a red black tree, Time complexity of O (LOGN), which greatly reduces the time to find.
Specific reference: 75331926
Related to red and black trees can be consulted: 53329023
Implementation of the 2.HashSet
Implement HashSet using the key part of HashMap
HashSet two methods that ensure element uniqueness, the hashcode () and the Equals () methods.
Implementation of the 3.Hashtable
HashMap is a lightweight implementation of Hashtable (non-thread-safe implementation), and they all complete the map interface.
The main differences are:
Thread-safe: Hashtable is thread-safe and uses the Sync keyword synchronized to decorate various methods for thread safety. HashMap is not thread-safe.
Efficiency: Single-threaded case, hashmap efficiency is higher than Hashtable, because Hashtable uses the Synchronized keyword, each call method will lock, reduce the efficiency. It is recommended to use CONCURRENTHASHMAP in multi-threaded situations.
4.CONCURRENTHASHMAP implementations
JDK6 Using segmented locks
JDK8 Use CPU CAS instructions, this is difficult to understand, you can directly with the interviewer said not very understand, just on the internet to see.
Cas,compare and swap abbreviations, Chinese translation into comparison and exchange.
5. Thread-Safe map
Hashtable,concurrenthashmap and Collections.synchronizedmap (map)
Collections.synchronizedmap (map): Pass a normal map as a parameter, return a map using synchronized to modify various methods, simple and rough implementation of thread safety.
Summary of Java Map-related knowledge points