HashMap is a popular interview topic due to its many nuances. The best preparation is often to read the source code of HashMap. The implementation is already discussed in detail in numerous articles.Here is the cheat sheet with key aspects to remember:
- Basic Principle: An internal array called
tablecontains buckets — sub-lists of items that share the same recalculated hash sums; - Hash sum recalculation to fit
intindexes incapacitycells of thetable; Rehashing: doubling the size of thetablewhen the number of occupied buckets reachesthreshold(capacity*loadFactor);- Inability to shrink once the
tableexpanded; - Two methods of collision resolution: chaining that is actually used in
HashMap, and open addressing alternative; - Concurrency options: over-synchronized
Hashtableand sophisticatedConcurrentHashMap; - Java 8 optimization: transforming the list in a bucket into a tree when it reaches 8 elements to improve access time from O(n) to O(log n) in the case of many collisions;
- Explicit use of bucket 0 for a
nullkey; - Relation to
HashSet– aHashMapwhere only keys are utilized; - Absence of order guarantees.
TreeMap and LinkedHashMap.