Java Reference
In-Depth Information
somewhat slower than with the other Set implementations (which are not sorted) be-
cause links must be traversed.
Note Check out Wikipedia's “Tree (data structure)” entry ( ht-
tp:// ) to learn
about trees.
TreeSet supplies four constructors:
TreeSet() createsanew,emptytreesetthatissortedaccordingtothenatural
Comparable interface.
TreeSet(Collection<? extends E> c) createsanewtreesetcon-
taining c 'selements,sortedaccordingtothenaturalorderingofitselements.All
elementsinsertedintothenewsetmustimplementthe Comparable interface.
This constructor throws ClassCastException when c 's elements do not
implement Comparable orarenotmutuallycomparable,and NullPoint-
erException when c contains the null reference.
TreeSet(Comparator<? super E> comparator) creates a new,
emptytreesetthatissortedaccordingtothespecified comparator .Passing
null to comparator implies that natural ordering will be used.
TreeSet(SortedSet<E> s) creates a new tree set containing the same
elements and using the same ordering as s . (I discuss sorted sets later in this
chapter.) This constructor throws NullPointerException when s con-
tains the null reference.
Listing 5-3 demonstrates a tree set.
Listing 5-3. A demonstration of a tree set with String elements sorted according to their natural
import java.util.Set;
import java.util.TreeSet;
class TreeSetDemo
public static void main(String[] args)
Set<String> ss = new TreeSet<>();
Search WWH ::

Custom Search