Java Reference
In-Depth Information
while (itr.hasNext()) {
String word = itr.next();
System.out.println(word);
}
A shorter alternative to the preceding code is to use a for-each loop over the ele-
ments of the set . As mentioned previously, the code behaves the same way but is
easier to write and read than the version with the while loop:
for (String word : words) {
System.out.println(word);
}
TreeSet versus HashSet
The examples in the preceding section used HashSet , but there's another class called
TreeSet that also implements the Set interface. A TreeSet uses an internal linked
data structure called a binary search tree to store its elements in sorted order. (We
will discuss binary tree implementations in detail in Chapter 17.) A TreeSet is effi-
cient for adding, removing, and searching, though it is a bit slower than a HashSet .
A TreeSet can be useful if you want to print the set and have the output ordered.
For example, the following code displays the sorted set of all three-letter words in
Moby Dick that start with “a”:
Set<String> words = new TreeSet<String>();
Scanner in = new Scanner(new File("mobydick.txt"));
while (in.hasNext()) {
String word = in.next();
word = word.toLowerCase();
if (word.startsWith("a") && word.length() == 3) {
words.add(word);
}
}
System.out.println("Three-letter 'a' words = " + words);
The code produces the following output:
Three-letter 'a' words = [act, add, ado, aft, age, ago, ah!,
ah,, aid, aim, air, alb, ale, ali, all, am,, am-, am:, and,
ant, any, apt, arc, are, ark, arm, art, as,, as-, as., ash,
ask, ass, at,, at., at;, at?, ate, awe, axe, aye]
A TreeSet can be used with data that has a natural ordering. This means that it will
work if its elements are of any type that implements the Comparable interface, such as
Integer or String . You can also provide your own object that specifies how to com-
pare elements, called a comparator . Comparators will be discussed in Chapter 13 when
we cover searching and sorting.
 
Search WWH ::




Custom Search