Junior — Middle
Can you explain the distinctive features of the TreeMap data structure?
sobes.tech AI
Answer from AI
TreeMap in Java is an implementation of the SortedMap interface that stores key-value pairs in sorted order by keys. Main features include:
- Sorted: elements are automatically ordered by key in natural order (if keys are Comparable) or by a provided Comparator.
- Based on a red-black tree: provides logarithmic time for access, insertion, and deletion.
- Cannot store null as a key: attempting to insert null as a key will throw a NullPointerException.
- Supports navigation methods: such as firstKey(), lastKey(), subMap(), headMap(), tailMap() for working with key ranges.
Example usage:
import java.util.TreeMap;
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "three");
map.put(1, "one");
map.put(2, "two");
for (Integer key : map.keySet()) {
System.out.println(key + " -> " + map.get(key));
}
// Output will be sorted by keys: 1, 2, 3