Java Reference
In-Depth Information
If you want a class that implements the
Set<T>
interface and do not need any meth-
ods beyond those in the
Set<T>
interface, you can use the concrete class
HashSet<T>
. So,
after all is said and done, if all you need is a collection class that does not allow elements
to occur more than once, then you can use the
HashSet<T>
class and need not worry
about all the other classes and interfaces in Display 16.1. The word “Hash” refers to the
fact that the
HashSet<T>
class is implemented using a hash table, which was introduced
in Chapter 15. The
HashSet<T>
, of course, implements all the methods in the
Set<T>
interface and adds no other methods beyond constructors. A summary of the
Hash-
Set<T>
constructors and other methods is given in Display 16.5. If you want to define
your own class that implements the
Set<T>
interface, you would probably be better off
using the
HashSet<T>
class rather than the
AbstractSet<T>
class as a base class.
HashSet<T>
Display 16.5
Methods in the
HashSet<T>
Class
The
HashSet<T>
class is in the
java.util
package.
The
HashSet<T>
class extends the
AbstractSet<T>
class and implements the
Set<T>
interface.
The
HashSet<T>
class implements all of the methods in the
Set<T>
interface (Display 16.3). The
only other methods in the
HashSet<T>
class are the constructors. The three constructors that do
not involve concepts beyond the scope of this topic are given below.
All the exception classes mentioned are the kind that are not required to be caught in a
catch
block or declared in a
throws
clause.
All the exception classes mentioned are in the package
java.lang
and so do not require any
import statement.
public
HashSet( )
Creates a new, empty set.
public
HashSet(Collection<? extends T> c )
Creates a new set that contains all the elements of
c
. Throws a
NullPointerException
if
c
is
null
.
public
HashSet(
int
initialCapacity)
Creates a new, empty set with the specified capacity.
Throws an
IllegalArgumentException
if
initialCapacity
is less than zero.
The methods are the same as those described for the
Set<T>
interface (Display 16.3.)
Display 16.6 shows a sample program that uses the
HashSet<T>
class. This program
is conceptually similar to the program in Display 15.38, in which sets containing strings
of round things and green things were manipulated in various 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