Middle
How many new objects are created when adding a new element to HashMap?
sobes.tech AI
Answer from AI
When adding a new element (key, value) to a HashMap, three new objects are usually created:
- The
Nodeobject: this is an internal data structure ofHashMap, representing an entry in the table. EachNodestores the hash of the key, the key itself, the value, and a reference to the nextNode(in case of collisions). - The key object (
key): even if the key already exists in memory, its hash code must be computed for use as a key inHashMap. Although the key object itself is not newly created, if the key is a primitive type, it will be automatically boxed (autoboxing) into the corresponding reference type (e.g.,inttoInteger), which will lead to the creation of a new wrapper object. If the key is a reference type, no new object is created; the existing object is used. - The value object (
value): similarly to the key, a primitive value will be boxed into an object wrapper. If the value is a reference type, no new object is created.
Thus, at minimum, one new object (Node) is created, and additional objects may be created due to autoboxing depending on the types of key and value.
Example:
// Creating a new Node
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
// ... other methods
}
When adding map.put(1, 10);:
- A new
Nodeis created. - The number
1(primitiveint) is boxed into anIntegerobject. - The number
10(primitiveint) is boxed into anIntegerobject.
Total: three new objects.
When adding map.put("abc", "xyz");:
- A new
Nodeis created. - The strings
"abc"and"xyz"most likely already exist in the string pool or were created earlier; new string objects are not created.
Total: one new object (Node).
Therefore, the exact number of new objects depends on the types of the key and value being added and their presence in memory (string pool, previously created instances). However, at least one Node object is always created.