Java Reference
In-Depth Information
765
Chapter 17 Generic Programming
C
HAPTER
G
OALS
ȗ
To understand the objective of generic programming
ȗ
To be able to implement generic classes and methods
ȗ
To understand the execution of generic methods in the virtual machine
ȗ
To know the limitations of generic programming in Java
ȗ
To understand the relationship between generic types and inheritance
ȗ
To learn how to constrain type variables
Generic programming involves the design and implementation of data structures
and algorithms that work for multiple types. You are already familiar with the
generic
ArrayList
class that can be used to produce array lists of arbitrary types.
In this chapter, you will learn how to implement your own generic classes.
765
766
17.1 Type Variables
Generic programming is the creation of programming constructs that can be used
with many different types. For example, the Java library programmers who
implemented the
ArrayList
class engaged in generic programming. As a result,
you can form array lists that collect different types, such as
ArrayList<String>, ArrayList<BankAccount>
, and so on.
The
LinkedList
class that we implemented in
Section 15.2
is also an example of
generic programmingȌyou can store objects of any class inside a
LinkedList
.
However, that
LinkedList
class achieves genericity with a different mechanism. It
is a single
LinkedList
class that stores values of type
Object
. You can, if you
like, store a
String
and a
BankAccount
object into the same
LinkedList
.
In Java, generic programming can be achieved with inheritance or with type
variables.