Java TreeMap-interview
Q1. What is TreeMap in Java, and how does it differ from HashMap?
TreeMap is a Map implementation that stores key-value pairs in sorted order of keys using a Red-Black Tree. Unlike HashMap, which is unordered, TreeMap guarantees sorted ordering.
Q2. Can a TreeMap have null keys and null values?
TreeMap does not allow null keys, but it allows multiple null values.
Q3. What is the time complexity of basic operations in TreeMap?
The time complexity for insertion, deletion, and lookup is O(log n), as TreeMap is based on a Red-Black Tree
Q4. What interfaces does TreeMap implement?
TreeMap implements NavigableMap, SortedMap, and indirectly Map, Collection, and Iterable.
Q5. How does TreeMap maintain sorting order, and can we customize it?
By default, TreeMap maintains natural ordering of keys (Comparable). Sorting can be customized by providing a Comparator at the time of TreeMap creation.