TreeSet
TreeSet is an implementation of the Set interface that automatically stores its elements in sorted order, based on their natural ordering (like ascending numbers or alphabetical order) or a custom sorting rule you provide.
1. What is TreeSet?
TreeSet is an implementation of the Set interface that automatically stores its elements in sorted order, based on their natural ordering (like ascending numbers or alphabetical order) or a custom sorting rule you provide.
2. Why is it used?
It's useful whenever you need a collection of unique elements that must also stay sorted at all times, without you needing to manually sort them yourself after every addition.
3. Real-Life Example
Think of a set of unique exam roll numbers that are always kept arranged in ascending order automatically, no matter in what order students originally submitted their forms. TreeSet maintains this kind of automatic sorted arrangement.
4. Syntax
javaTreeSet<DataType> setName = new TreeSet<>();
5. Example Program
javaimport java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(50); numbers.add(10); numbers.add(30); System.out.println(numbers); } }
Output:
[10, 30, 50]6. Key Points to Remember
TreeSetkeeps elements sorted automatically at all times.- It does not allow
nullelements, since sorting anullvalue doesn't make sense. TreeSetis generally slower thanHashSetdue to the extra work of maintaining sorted order.