Concepts of Programming Languages

(Sean Pound) #1
9.9 Generic Subprograms 425

float flt_list[100];

...
generic_sort(flt_list, 100);


The templated functions of C++ are a kind of poor cousin to a subprogram
in which the types of the formal parameters are dynamically bound to the types
of the actual parameters in a call. In this case, only a single copy of the code
is needed, whereas with the C++ approach, a copy must be created at compile
time for each different type that is required and the binding of subprogram
calls to subprograms is static.

9.9.2 Generic Methods in Java 5.0


Support for generic types and methods was added to Java in Java 5.0. The name
of a generic class in Java 5.0 is specified by a name followed by one or more
type variables delimited by pointed brackets. For example,

generic_class<T>

where T is the type variable. Generic types are discussed in more detail in
Chapter 11.
Java’s generic methods differ from the generic subprograms of C++ in
several important ways. First, generic parameters must be classes—they can-
not be primitive types. This requirement disallows a generic method that
mimics our example in C++, in which the component types of arrays are
generic and can be primitives. In Java, the components of arrays (as opposed
to containers) cannot be generic. Second, although Java generic methods can
be instantiated any number of times, only one copy of the code is built. The
internal version of a generic method, which is called a raw method, operates
on Object class objects. At the point where the generic value of a generic
method is returned, the compiler inserts a cast to the proper type. Third, in
Java, restrictions can be specified on the range of classes that can be passed
to the generic method as generic parameters. Such restrictions are called
bounds.
As an example of a generic Java 5.0 method, consider the following skeletal
method definition:

public static <T> T doIt(T[] list) {

...
}


This defines a method named doIt that takes an array of elements of a generic
type. The name of the generic type is T and it must be an array. Following is
an example call to doIt:

doIt<String>(myList);
Free download pdf