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
table
contains buckets — sub-lists of items that share the same recalculated hash sums; - Hash sum recalculation to fit
int
indexes incapacity
cells of thetable
; Rehashing
: doubling the size of thetable
when the number of occupied buckets reachesthreshold
(capacity*loadFactor
);- Inability to shrink once the
table
expanded; - Two methods of collision resolution: chaining that is actually used in
HashMap
, and open addressing alternative; - Concurrency options: over-synchronized
Hashtable
and 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
null
key; - Relation to
HashSet
– aHashMap
where only keys are utilized; - Absence of order guarantees.
TreeMap
and LinkedHashMap
.