Java Reference
In-Depth Information
that the type of object that the collection manages can be established
when an object of that collection type is instantiated.
For example, to create a LinkedList of String objects, we would
instantiate a collection object in the following way:
KEY CONCEPT
The classes of the Java Collections
API are implemented as generic
types.
LinkedList<String> myStringList = new LinkedList<String>();
Similarly, to create a LinkedList of Book objects, we would instantiate the col-
lection as follows:
LinkedList<Book> myBookList = new LinkedList<Book>();
By specifying the type stored in the collection, we gain two advantages:
Only objects of the appropriate type can be added to the collection.
When an object is removed from the collection, its type is already estab-
lished, avoiding the need to cast it to an appropriate type.
The myStringList object can store only String objects, and the
myBookList collection can store only Book objects. Keep in mind that
these include objects related to the specified type by inheritance. For
example, if a Dictionary class is derived from Book , then we could
store a Dictionary object in the myBookList collection. After all, if
we're using inheritance correctly, a Dictionary is-a Book .
If no specific type is specified when the collection object is created, the collec-
tion is defined as containing references of the Object class, which means they can
store any type of object. This makes the use of the collections classes consistent
with earlier versions of Java that did not include generic specifications.
The details of the collection classes and the techniques for defining a generic
class go beyond the scope of this topic and so are not explored further here.
KEY CONCEPT
Generic classes ensure type
compatibility among the objects
stored by the collection.
SELF-REVIEW QUESTIONS (see answers in Appendix N)
SR 13.17 What is the Java Collections API?
SR 13.18 What is a generic type, and how does it relate to the Java Collections
API?
 
Search WWH ::




Custom Search