[Texas PLT logo]

COMP 202: Principles of Object-Oriented Programming II

  Generic IList Framework & Example Algorithms  

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 IList interface:

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 IList<Integer> contains Integer objects.

In the definition of the execute() method, however, we see <R,P>, and that defines two more type parameters R and 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 execute() method, and P is the type of the inp varargs.

Furthermore, the definition of execute() spells out exactly what kind of visitor it needs:

The actual types of R and P will be deduced at the call site for execute(); they are not nailed down in this definition. The compiler, however, will make sure that all occurrences of R, P and 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.

Take a look at the definition of the IListAlgo interface:

The visitor has three type parameters, E, R and 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 IMTList and INEList 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

 

 

 

 

 

  Generic IList Framework &amp; Example Algorithms  

URL: http://www.clear.rice.edu/comp202/08-fall/lectures/genIList/index.shtml
Copyright © 2008-2010 Mathias Ricken and Stephen Wong