Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 17: java.util Part 1: The Collections Framework 455


The TreeSet Class


TreeSetextendsAbstractSetand implements theNavigableSetinterface. It creates a
collection that uses a tree for storage. Objects are stored in sorted, ascending order. Access
and retrieval times are quite fast, which makesTreeSetan excellent choice when storing large
amounts of sorted information that must be found quickly.
TreeSetis a generic class that has this declaration:


class TreeSet<E>

Here,Especifies the type of objects that the set will hold.
TreeSethas the following constructors:


TreeSet( )
TreeSet(Collection<? extends E>c)
TreeSet(Comparator<? super E>comp)
TreeSet(SortedSet<E>ss)

The first form constructs an empty tree set that will be sorted in ascending order according
to the natural order of its elements. The second form builds a tree set that contains the elements
ofc.The third form constructs an empty tree set that will be sorted according to the comparator
specified bycomp.(Comparators are described later in this chapter.) The fourth form builds
a tree set that contains the elements ofss.
Here is an example that demonstrates aTreeSet:


// Demonstrate TreeSet.
import java.util.*;


class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set.
TreeSet ts = new TreeSet();


// Add elements to the tree set.
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");

System.out.println(ts);
}
}


The output from this program is shown here:


[A, B, C, D, E, F]

As explained, becauseTreeSetstores its elements in a tree, they are automatically arranged
in sorted order, as the output confirms.

Free download pdf