Java Reference
In-Depth Information
and there are some fundamental differences between the two approaches to generic
types. For the most part, Java's approach is simpler to use.
A word of warning: If you have a background in C++, it is important not to jump to
conclusions about how generics work in Java. The two approaches to generic code differ
in subtle but fundamental ways.
A principal advantage of generic code is that it will automatically work with the type of
data passed to its type parameter. Many algorithms are logically the same no matter what
type of data they are being applied to. For example, a Quicksort is the same whether it is
sorting items of type Integer , String , Object , or Thread . With generics, you can define an
algorithm once, independently of any specific type of data, and then apply that algorithm
to a wide variety of data types without any additional effort.
It is important to understand that Java has always given you the ability to create general-
ized classes, interfaces, and methods by operating through references of type Object . Be-
cause Object is the superclass of all other classes, an Object reference can refer to any type
of object. Thus, in pre-generics code, generalized classes, interfaces, and methods used Ob-
ject references to operate on various types of data. The problem was that they could not
do so with type safety because casts were needed to explicitly convert from Object to the
actual type of data being operated upon. Thus, it was possible to accidentally create type
mismatches. Generics add the type safety that was lacking because they make these casts
automatic and implicit. In short, generics expand your ability to reuse code and let you do
so safely and reliably.
A Simple Generics Example
Before discussing any more theory, it's best to look at a simple generics example. The fol-
lowing program defines two classes. The first is the generic class Gen , and the second is
GenDemo , which uses Gen .
Search WWH ::




Custom Search