One of the new features strongly requested by Java programmers is generics, which
is finally included in the language from Java 5.0. The biggest advantage of adding
generics to Java is the improvement in using Java Collections Framework classes
such as ArrayList. Prior to Java 5.0, these collections could include any type of objects.
For example, if you have a list (either ArrayList or LinkedList), there are no restrictions
on the types of objects you can add to the list. In other words, we can add
objects from Integer, String, Person, Vehicle, and other classes to a single list. In
practice, however, we rarely need such heterogeneous collections in which the
elements are of different types. What we need most in practice is a homogeneous
collection in which the elements are of the same type, such as a list of Vehicle
objects, a set of Person objects, and so forth. But prior to Java 5.0, we could not
declare such homogeneous collections. It is therefore up to the programmers to
ensure that only the valid objects are added to a collection. If the programmers
make a mistake and inadvertently write an erroneous code that adds objects of
invalid types to a collections, a runtime error most likely will result. Addition of the
generics mechanism allows the programmers to declare homogeneous collections,
and any attempt in the code to add invalid objects will be caught at compile time. Detecting
errors at compile time is considered far superior to detecting errors at runtime.
We’ve already seen simple examples of the generics mechanism when defining
a homogeneous collection in Chapter 10. In this chapter, we provide a more indepth
coverage of generics, such as defining our own generic classes. We begin with
the basics and gradually introduce variations and details. We show how to define a
simple generic linked list class by adding the generics to the linked node structure
we learned in Chapter 16. We conclude the chapter with a discussion of advanced
topics and common errors.
To learn more about the book this website supports, please visit its Information Center.