Java.Collections.How many new objects are created when you add a new element to a HashMap?

Excellent question, Stanley! Let’s break it down:

How many new objects are created when you do map.put(key, value) in a HashMap?

It depends on a few factors like resizing, collisions, and whether the key already exists. But in the most common case, here’s what happens:


Typical case: Adding a new key-value pair

Code:

Map<String, String> map = new HashMap<>();
map.put("foo", "bar");

What happens internally?

  1. No resizing is triggered (i.e. capacity is sufficient).
  2. No collision in the target bucket.
  3. The key does not already exist.

➕ Objects created:

ObjectDescription
🔹 1 Node<K,V>HashMap stores each entry in a Node object (a linked list node). Created when inserting a new key.
🔹 0 new keys/valuesIf the key and value already exist as references (like string literals or reused objects), no new ones are created.

🧮 Total: 1 new object — the internal Node<K, V>.

⚠️ Cases that add more objects:

1. Resizing (rehash())

If the number of elements exceeds capacity × load factor, HashMap resizes:

  • A new array (twice the size) is created.
  • All existing Node or TreeNode objects are reinserted (but not recreated — references are reused).

🧮 1 new table array is created
(plus some temporary helper objects during rehashing).

2. Treeification

If too many collisions occur in a bucket (≥8 nodes and table size ≥64):

  • Linked list of Node objects is converted into TreeNode objects.
  • New TreeNode instances are created for existing entries.

🧮 Up to N new TreeNode objects (replacing N existing Node objects).

3. Autoboxing

If you’re using primitive types as keys/values (e.g. int), autoboxing creates wrapper objects like Integer.

map.put(42, "value"); // creates new Integer(42)

🧮 1 new Integer if not cached (Java caches small integers -128 to 127).


🧠 TL;DR

ScenarioObjects created
Basic put() with new key✅ 1 Node<K,V>
Key/value are new primitives✅ +1 or +2 (boxing)
Resizing happens✅ +1 new array
Treeification occurs✅ +N TreeNodes
This entry was posted in Без рубрики. Bookmark the permalink.