This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
Map is one of the commonly used collections in Java, and its key implementation classes include HashMap, LinkedHashMap, TreeMap, and Hashtable.
Note: Map is a Collection, but not a Collection.
HashMap
The underlying HashMap uses arrays + linked lists/red-black trees (JDK 1.8). The uniqueness of the HashMap keys is guaranteed by hashcode, so if the keys are entities, you need to override equals() and hashcode().
LinkedHashMap
LinkedHashMap is a special form of HashMap, where the entries add before and after to make the underlying form an array + two-way list. A bidirectional linked list records the order of the entire table, so the LinkedHashMap is ordered.
static class Entry<K.V> extends HashMap.Node<K.V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next); }}Copy the code
The structure diagram of HashMap and LinkedHashMap is as follows:
Hashtable
Hashtable is thread-safe, but has been deprecated due to performance issues. In a multithreaded environment, you can use the Collections. SynchronizedMap or ConcurrentHashMap, the former more lock, so the performance of the latter is better.
Other Map
- IdentityHashMap allows null keys and does not guarantee consistent order of insert traversals. The special thing is to use == instead of equals to compare keys for equality.
- WeakHashMap key misreports the weak reference of the real object, so the key-value pair will be deleted automatically as the real object is reclaimed, which is not commonly used.
- TreeM is non-thread-safe and is implemented based on a red-black tree, because the tree is always in balance and therefore has no tuning preferences. However, you can override the comparator to implement custom sorting.
conclusion
key | value | capacity | capacity | order | The parent class | hashcode | instructions | |
---|---|---|---|---|---|---|---|---|
HashMap | Allow null | Allow null | 16 | 2n | A disorderly | AbstractMap | recalculate | Non-thread-safe |
LinkedHashMap | Allow null | Allow null | 16 | 2n | The orderly | AbstractMap | recalculate | Non-thread-safe |
TreeMap | Do not allow null | Allow null | 16 | 2n | Natural ordering | AbstractMap | recalculate | Non-thread-safe |
ConcurrentHashMap | Do not allow null | Do not allow null | 16 | 2n | A disorderly | AbstractMap | recalculate | Lock section technique |
Hashtable | Do not allow null | Do not allow null | 11 | 2n+1 | A disorderly | Dictionary | Direct use of | Thread safety |