Java Reference
In-Depth Information
702
You will see later in this chapter when it is better to choose a hash set over a tree set.
For now, let's look at an example where we choose a hash set. To keep the example
simple, we'll store only strings, not Printer objects.
Set<String> names = new HashSet<String>();
Note that we store the reference to the HashSet<String> object in a
Set<String> variable. After you construct the collection object, the
implementation no longer matters; only the interface is important.
Adding and removing set elements is straightforward:
names.add("Romeo");
names.remove("Juliet");
The contains method tests whether an element is contained in the set:
if (names.contains("Juliet")) . . .
Finally, to list all elements in the set, get an iterator. As with list iterators, you use the
next and hasNext methods to step through the set.
Iterator<String> iter = names.iterator();
while (iter.hasNext())
{
String name = iter.next();
Do something with name
}
Or, as with arrays and lists, you can use the Ȓfor eachȓ loop instead of explicitly using
an iterator:
for (String name : names)
{
Do something with name
}
Note that the elements are not visited in the order in which you inserted them.
Instead, they are visited in the order in which the HashSet keeps them for rapid
execution of its methods.
An iterator visits all elements in a set.
Search WWH ::




Custom Search