Sobes.tech
Junior — Middle

Kuidas lisada uus element TreeMap struktuuri?

sobes.tech AI

Vastus AI-lt

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. This involves:

  • First, searching for the position for the new key in the tree by comparing keys.
  • 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.