Java Reference
In-Depth Information
Abstract
Collection<T>
The abstract class
AbstractCollection<T>
is a skeleton class for the
Collection<T>
interface. Although it is perfectly legal, you seldom, if ever, need to define a derived class
of the
AbstractCollection<T>
class. Instead, you normally define a derived class of
one of the descendent classes of the
AbstractCollection<T>
class.
If you want a class that implements the
Set<T>
interface and do not need any
methods 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 Section 15.5. 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
HashSet<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 are probably 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 next.
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).