Loading

Q1. What is a TreeSet in Java?

A TreeSet is a part of Java’s Collection Framework that implements the Set interface and uses a Red-Black Tree internally to store elements in sorted order without duplicates.





Q2. How does TreeSet maintain the order of elements?

TreeSet maintains elements in ascending order by default using their natural ordering or by a custom Comparator provided during creation.





Q3. What is the difference between TreeSet and HashSet?
  • HashSet: Stores elements in random order, backed by a HashMap.
  • TreeSet: Stores elements in sorted order, backed by a TreeMap.




Q4. Can TreeSet store null values? Why or why not?

TreeSet allows only one null value, but if you try to add more or compare null with other elements, it throws a NullPointerException because sorting requires comparison.





Q5. What is the time complexity of basic operations in TreeSet?
  • Insertion, Deletion, and Search take O(log n) time because TreeSet is based on a balanced Red-Black Tree.





Q6. How can you create a TreeSet with a custom sorting order?

This shows that TreeSet is not limited to natural ordering; it can adapt to your sorting requirements.

TreeSet<String> cities = new TreeSet<>((a, b) -> b.compareTo(a));  

cities.add("Delhi");  

cities.add("Mumbai");  

cities.add("Kolkata");  

System.out.println(cities);  // [Mumbai, Kolkata, Delhi] (Descending order)