Java Reference
In-Depth Information
classes should implement. A summary of these operations (method headings) for the
interface are given in Display 16.2. A more complete description can
be found in Appendix 5. Because an interface is a type, you can define methods with
a parameter of type
Collection<T>
. That parameter can be filled in with an argu-
ment that is an object of any class in the collection framework (that is, any class that
implements the
Collection<T>
interface). This turns out to be a very powerful tool.
Let's explore the possibilities. So far, we have seen one class that implements the
Collection<T>
interface, namely the class
. In addition to the meth-
Collection<T>
ArrayList<T>
ods given in Chapter 14 for the
class also
implements all the methods given in Display 16.2. There are a number of different
predefined classes that implement the
class, the
ArrayList<T>
ArrayList<T>
interface, and you can define
Collection<T>
your own classes that implement the
interface. If you write a method
Collection<T>
to manipulate a parameter of type
, it will work for all of these
Collection<T>
classes. Also, the methods in the
interface ensure that you can inter-
mix the use of different collection classes. For example, consider the method
Collection<T>
public boolean containsAll(Collection<?> collectionOfTargets)
You can use this with two
objects (one the calling object and one the argu-
ment) to see if one contains all the elements of the other. The two
ArrayList<T>
objects
do not even have to have the same base type. Moreover, you can also use it with an
ArrayList<T> object and an object of any other class that implements the Collection<T>
interface to compare the elements in these two different kinds of Collection<T> objects.
ArrayList<T>
Display 16.2 Method Headings in the Collection<T> Interface (part 1 of 3)
The Collection<T> interface is in the java.util package.
CONSTRUCTORS
Although not officially required by the interface, any class that implements the Collection<T>
interface should have at least two constructors: a no-argument constructor that creates an empty
Collection<T> object, and a constructor with one parameter of type Collection<? extends
T> that creates a Collection<T> object with the same elements as the constructor argument.
The interface does not specify whether the copy produced by the one-argument constructor is a
shallow copy or a deep copy of its argument.
METHODS
boolean isEmpty( )
Returns true if the calling object is empty; otherwise returns false .
public boolean contains(Object target)
Returns true if the calling object contains at least one instance of target . Uses target.equals
to determine if target is in the calling object.
(continued)
Search WWH ::




Custom Search