Java › Collections Framework
How does HashMap's internal implementation work (hashing, bucket array, treeification), and how did its collision-handling strategy change in Java 8?
AdvancedAnswer
HashMap stores entries in an internal array of buckets, using a key's hashCode() (further scrambled via an internal hash-spreading function to reduce clustering) to determine the target bucket index; collisions (multiple keys mapping to the same bucket) were historically resolved via a linked list of entries within that bucket -- as of Java 8, when a single bucket's linked list grows beyond a threshold (default 8 entries, and the overall table has at least 64 buckets), that bucket is "treeified" into a self-balancing red-black tree instead, changing worst-case lookup within a severely collision-heavy bucket from O(n) to O(log n), a defense against both accidental hash collisions and deliberate hash-flooding denial-of-service attacks.
// Conceptual illustration of what happens internally with many colliding keys
Map<CustomKey, String> map = new HashMap<>();
// If many CustomKey instances have colliding/identical hashCode() values,
// their bucket's internal linked list can grow long --
// Java 8+ automatically converts it to a red-black tree once it exceeds 8 entries
// (assuming the table has at least 64 buckets), bounding worst-case lookup to O(log n)Real-world example A security audit of a web application accepting arbitrary user-controlled strings as HashMap keys confirms that even a deliberately crafted hash-collision attack (submitting many strings engineered to collide) is mitigated by Java 8's automatic treeification, preventing the O(n²) denial-of-service degradation that affected older Java versions lacking this protection.