Java Reference
In-Depth Information
our union and intersection methods can be achieved by using the HashSet<T> add-
All and removeAll methods. To output the items in a HashSet<T> object we define an
outputSet method. This method uses iterators, which are not discussed until Section
16.3, so for now you can ignore the details of how outputSet works.
In general, it is recommended that you use the collection classes unless they do not
provide the functionality you need for your program. For example, say that you want
every item added to the set to have a reference to the set that contains it. This could be
useful if you want to determine whether two items are in the same set—you could just
follow the reference to the containing set for each item and see whether they were the
same. Without such a reference you would have to invoke the contains method for
every set to learn whether the items were in the same set. If this were an important fea-
ture for your program, you might want to develop your own class instead of using one of
the collection classes. If the collection classes were sufficient, the result would be shorter
code that is generally easier to develop and maintain. Moreover, the collection classes like
HashSet<T> have been designed with efficiency and scalability in mind.
Display 16.6 HashSet<T> Class Demo (part 1 of 3)
1 import java.util.HashSet;
2 import java.util.Iterator;
3 public class HashSetDemo
4{
5
private static void outputSet(HashSet<String> set)
The outputSet method
uses an iterator to
print the contents of a
HashSet<T> object.
Iterators are described
in Section 16.3.
6
{
7
Iterator<String> i = set.iterator( );
8
while (i.hasNext( ))
9
System.out.print(i.next( ) + " ");
10
System.out.println( );
11
}
12
public static void main(String[] args)
13
{
14
HashSet<String> round = new HashSet<String>( );
15
HashSet<String> green = new HashSet<String>( );
16
// Add some data to each set
17
round.add("peas");
18
round.add("ball");
19
round.add("pie");
20
round.add("grapes");
21
green.add("peas");
22
green.add("grapes");
23
green.add("garden hose");
24
green.add("grass");
Search WWH ::




Custom Search