Sobes.tech
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:

  1. The Node object: this is an internal data structure of HashMap, representing an entry in the table. Each Node stores the hash of the key, the key itself, the value, and a reference to the next Node (in case of collisions).
  2. The key object (key): even if the key already exists in memory, its hash code must be computed for use as a key in HashMap. 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., int to Integer), 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.
  3. 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 Node is created.
  • The number 1 (primitive int) is boxed into an Integer object.
  • The number 10 (primitive int) is boxed into an Integer object.

Total: three new objects.

When adding map.put("abc", "xyz");:

  • A new Node is 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.

How many new objects are created when adding a new… - sobes.tech