Java Reference
In-Depth Information
Display 16.6 HashSet<T> Class Demo (part 3 of 3)
ball in set round? true
ball in set green? false
ball and peas in same set? True
pie and grass in same set? false
Union of green and round:
garden hose grass peas ball pie grapes
Intersection of green and round:
peas grapes
ways using our own Set<T> class implemented with linked lists. However, the code
listing in Display 16.6 uses the HashSet<T> class in place of our custom Set<T> class.
Nevertheless, most of the code is identical because the Set<T> class was designed
to have an interface similar to the HashSet<T> class. Both have add and contains
methods. Functionality similar to our union and intersection methods can be
achieved by using the HashSet<T> addAll 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 are
the same. Without such a reference, you would have to invoke the contains method
for every set to learn whether the items are in the same set. If this were an important
feature 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 such as HashSet<T> have been designed with efficiency and scalability in mind.
If you want a class that implements the List<T> interface and do not need any
methods beyond those in this interface, you can use the ArrayList<T> or Vector<T>
class. So, after all is said and done, if all you need is a collection class that allows
elements to occur more than once, or you need a collection that orders its elements as
on a list (that is, as in an array), or you need a class that has both of these properties,
then you can use the ArrayList<T> or Vector<T> class and need not worry about all
the other classes and interfaces in Display 16.1. The ArrayList<T> and Vector<T>
classes implement all the methods in the List<T> interface. A table of methods for the
ArrayList<T> class was given in Chapter 14 and a more complete table is given in
Vector<T>
 
Search WWH ::




Custom Search