How do you use TreeSet?
TreeSet is a collection class in Java that implements the Set interface, used to store a group of elements while maintaining their order. It utilizes a Red-Black tree data structure to store elements and can sort them based on their natural order or a specified comparator.
To use TreeSet, you first need to create a TreeSet object and specify the type of elements, for example:
TreeSet<Integer> treeSet = new TreeSet<>();
Then you can add elements to the TreeSet using the add() method.
treeSet.add(10);
treeSet.add(5);
treeSet.add(20);
You can use the iterator() method or a foreach loop to iterate over the elements in a TreeSet, for example:
Iterator<Integer> iterator = treeSet.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
for(Integer num : treeSet){
System.out.println(num);
}
TreeSet also offers some other methods to operate on the collection, such as the remove() method to delete a specified element, the contains() method to check if the collection contains a specific element, and the size() method to retrieve the size of the collection.
It is important to note that the elements in a TreeSet must be comparable, meaning that the elements must implement the Comparable interface or a comparator must be specified when constructing the TreeSet. If the elements are not comparable, a ClassCastException will be thrown.