Java Reference
In-Depth Information
headSet("New York"): [Beijing, London]
tailSet("New York"): [New York, Paris, San Francisco]
lower("P"): New York
higher("P"): Paris
floor("P"): New York
ceiling("P"): Paris
pollFirst(): Beijing
pollLast(): San Francisco
New tree set: [London, New York, Paris]
The example creates a hash set filled with strings, then creates a tree set for the same strings. The
strings are sorted in the tree set using the compareTo method in the Comparable interface.
The elements in the set are sorted once you create a TreeSet object from a HashSet
object using new TreeSet<String>(set) (line 16). You may rewrite the program to
create an instance of TreeSet using its no-arg constructor, and add the strings into the
TreeSet object.
treeSet.first() returns the first element in treeSet (line 20), and treeSet.last()
returns the last element in treeSet (line 21). treeSet.headSet("New York") returns the
elements in treeSet before New York (lines 22-23). treeSet.tailSet("New York")
returns the elements in treeSet after New York, including New York (lines 24-25).
treeSet.lower("P") returns the largest element less than P in treeSet (line 28).
treeSet.higher("P") returns the smallest element greater than P in treeSet (line 29).
treeSet.floor("P") returns the largest element less than or equal to P in treeSet
(lineĀ 30). treeSet.ceiling("P") returns the smallest element greater than or equal to P
in treeSet (line 31). treeSet.pollFirst() removes the first element in treeSet and
returns the removed element (line 32). treeSet.pollLast() removes the last element in
treeSet and returns the removed element (line 33).
Note
All the concrete classes in Java Collections Framework (see FigureĀ 20.1) have at least
two constructors. One is the no-arg constructor that constructs an empty collection.
The other constructs instances from a collection. Thus the TreeSet class has the con-
structor TreeSet(Collection c) for constructing a TreeSet from a collection c .
In this example, new TreeSet<>(set) creates an instance of TreeSet from the
collection set .
Tip
If you don't need to maintain a sorted set when updating a set, you should use a hash
set, because it takes less time to insert and remove elements in a hash set. When you
need a sorted set, you can create a tree set from the hash set.
If you create a TreeSet using its no-arg constructor, the compareTo method is used to com-
pare the elements in the set, assuming that the class of the elements implements the Comparable
interface. To use a comparator, you have to use the constructor TreeSet(Comparator
comparator) to create a sorted set that uses the compare method in the comparator to order
the elements in the set.
Listing 21.5 gives a program that demonstrates how to sort elements in a tree set using the
Comparator interface.
L ISTING 21.5
TestTreeSetWithComparator.java
1 import java.util.*;
2
 
 
Search WWH ::




Custom Search