Sobes.tech
Junior — Middle

How is a new element added to a TreeMap structure?

sobes.tech AI

Answer from AI

In Java, TreeMap implements a data structure based on a red-black tree, which stores keys in sorted order.

Adding a new element is done using the put(key, value) method. In this process:

  • The position for the new key in the tree is first searched using key comparison.
  • If the key already exists, the value is updated.
  • If the key is new, a new node is created and inserted into the tree while maintaining balance.

Example:

TreeMap<Integer, String> map = new TreeMap<>();
map.put(10, "ten");
map.put(5, "five");
map.put(20, "twenty");

As a result, the keys will be stored in sorted order: 5, 10, 20.