Java Reference
In-Depth Information
String[] fruits = {"apples", "pears", "grapes", "ba-
nanas", "kiwis"};
for (String fruit: fruits)
dump("ss:", ss);
static void dump(String title, Set<String> ss)
System.out.print(title+" ");
for (String s: ss)
System.out.print(s+" ");
Because String implements Comparable ,itislegalforthisapplicationtousethe
TreeSet() constructor to insert the contents of the fruits array into the set.
When you run this application, it generates the following output:
ss: apples bananas grapes kiwis pears
The HashSet class provides a set implementation that is backed by a hashtable data
structure(implementedasa HashMap instance,discussedlater,whichprovidesaquick
class provides no ordering guarantees for its elements, HashSet is much faster than
TreeSet . Furthermore, HashSet permits the null reference to be stored in its in-
Note Check out Wikipedia's “Hash table” entry ( ht-
tp:// ) to learn about hashtables.
HashSet supplies four constructors:
HashSet() creates a new, empty hashset where the backing HashMap in-
these items mean when I discuss HashMap later in this chapter.
HashSet(Collection<? extends E> c) createsanewhashsetcon-
taining c 's elements. The backing HashMap has an initial capacity sufficient
Search WWH ::

Custom Search