1. What is a TreeSet in Java?
Answer:
Explanation:
TreeSet in Java is a NavigableSet implementation that uses a Red-Black tree for storage.
2. How are elements stored in a TreeSet?
Answer:
Explanation:
Elements in a TreeSet are stored in a sorted (ascending) order.
3. Can a TreeSet contain duplicate elements?
Answer:
Explanation:
TreeSet cannot contain duplicate elements; it only allows unique elements.
4. What must elements of a TreeSet implement?
Answer:
Explanation:
Elements in a TreeSet must implement the Comparable interface, or you can provide a Comparator at TreeSet creation time for custom sorting.
5. What happens if you try to add a null element to a TreeSet?
Answer:
Explanation:
Attempting to add a null element to a TreeSet will result in a NullPointerException.
6. How do you remove an element from a TreeSet?
Answer:
Explanation:
The remove() method is used to remove a specific element from a TreeSet.
7. How do you access the first element in a TreeSet?
Answer:
Explanation:
The first() method returns the first (lowest) element currently in the TreeSet.
8. What is the time complexity of basic operations like add, remove, and search in a TreeSet?
Answer:
Explanation:
Basic operations in a TreeSet, such as add, remove, and search, have a time complexity of O(log n).
9. Can a TreeSet be synchronized?
Answer:
Explanation:
A TreeSet can be synchronized by using Collections.synchronizedSortedSet().
10. How do you get a reverse order view of the elements in a TreeSet?
Answer:
Explanation:
The descendingSet() method returns a reverse order view of the elements contained in the TreeSet.