COMP 202: Principles of Object-Oriented Programming II← Generic IList Framework & Example Algorithms →
|Home — Fall 2008|||||Information|||||Resources|||||Exam Resources|||||OwlSpace|||||COMP 201|
Let's finish up where we were last lecture...
For the rest of today's discussion, we will examine how generics can be used to reformulate our immutable list framework to produce a much more type-safe system. Here's the code: genIList.zip. You also browse individual files.
The definition of visitors in the generic IList framework is of particular interest: It shows the use of paremeterized methods, upper and lower bounds and multiple type parameters very well.
Here is the definition of the
First, note the
<E> in the interface declaration: It tells you that we are defining
a list containing instances of
E, whatever that may be. For example, an
In the definition of the
execute() method, however, we see
<R,P>, and that defines
two more type parameters
P that are only valid for this one method. This is an example
of a parameterized method inside a parameterized class.
R is the type of the return value of the
P is the type of the
Furthermore, the definition of
execute() spells out exactly what kind of visitor it needs:
E, or supertypes of it. Supertypes are allowed too, because a visitor that is designed to handle any object of type
Numbercan certainly also handle objects or type
Integer. We therefore make use of lower bounds.
The actual types of
P will be deduced at the call site for
they are not nailed down in this definition. The compiler, however, will make sure that all occurrences of
E at a call site are consistent, so you cannot execute a visitor for lists of numbers
on a list of strings, or pass string varargs to a visitor requiring numbers.
The visitor has three type parameters,
P, and they specify
the types of the list elements the visitor can process, the return value, and the varargs, respectively. If you
look at the definition of the two visitor methods, you can see that they accept
instances whose type parameter is
E or a subclass thereof. This is an example of an upper bound.
Examples of algorithms on the generic IList framework
Copyright © 2008-2010 Mathias Ricken and Stephen Wong