1. What is a TreeMap in Java?
Answer:
Explanation:
TreeMap is a Map implementation that uses a Red-Black tree, providing a sorted map.
2. How are the keys in a TreeMap stored?
Answer:
Explanation:
TreeMap stores its keys in ascending order, according to the natural ordering of its keys.
3. Can a TreeMap contain duplicate keys?
Answer:
Explanation:
TreeMap cannot contain duplicate keys. Each key can map to exactly one value.
4. Which interface must the keys in a TreeMap implement?
Answer:
Explanation:
The keys in a TreeMap must implement the Comparable interface or be used with a Comparator to determine their order.
5. What happens when a null key is inserted into a TreeMap?
Answer:
Explanation:
Inserting a null key into a TreeMap will result in a NullPointerException, as TreeMap relies on natural ordering or comparators.
6. What method do you use to get all keys from a TreeMap?
Answer:
Explanation:
The keySet() method returns a set view of the keys contained in the TreeMap.
7. How do you retrieve the first key in a TreeMap?
Answer:
Explanation:
The firstKey() method retrieves the first (lowest) key currently in the TreeMap.
8. What is the default initial capacity of a TreeMap?
Answer:
Explanation:
TreeMap does not have an initial capacity like HashMap because it's based on a Red-Black tree structure.
9. Can you store a null value in a TreeMap?
Answer:
Explanation:
TreeMap allows null values, but it does not support null keys.
10. How does TreeMap compare keys for sorting?
Answer:
Explanation:
TreeMap compares keys either by their natural ordering or by a specified Comparator at the time of TreeMap creation.