Java Reference
In-Depth Information
String[] fruits = {"apples", "pears", "grapes", "ba-
nanas", "kiwis"};
for (String fruit: fruits)
ss.add(fruit);
dump("ss:", ss);
}
static void dump(String title, Set<String> ss)
{
System.out.print(title+" ");
for (String s: ss)
System.out.print(s+" ");
System.out.println();
}
}
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
HashSet
The
HashSet
class provides a set implementation that is backed by a hashtable data
structure(implementedasa
HashMap
instance,discussedlater,whichprovidesaquick
waytodetermineifanelementhasalreadybeenstoredinthisstructure).Althoughthis
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-
stances.
Note
Check out Wikipedia's “Hash table” entry (
ht-
tp://en.wikipedia.org/wiki/Hash_table
) to learn about hashtables.
HashSet
supplies four constructors:
•
HashSet()
creates a new, empty hashset where the backing
HashMap
in-
stancehasaninitialcapacityof16andaloadfactorof0.75.Youwilllearnwhat
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