25.2. Motivation for Generic MethodsOverloaded methods are often used to perform similar operations on different types of data. To motivate the concepte of generic methods, let's begin with an example (Fig. 25.1) that contains three overloaded PrintArray methods (lines 1925, 2834 and 3743). These methods display the elements of an Integer array, a Double array and a Char array, respectively. In Section 25.3, we reimplement this program more concisely and elegantly using a single generic method. Figure 25.1. Displaying arrays of different types using overloaded methods
The program begins by declaring and initializing three arrayssix-element Integer array integerArray (line 6), seven-element Double array doubleArray (line 7) and fiveelement Char array charArray (line 8). Then lines 1015 output the arrays. When the compiler encounters a method call, it attempts to locate a method declaration that has the same method name and parameters that match the argument types in the method call. In this example, each PrintArray call exactly matches one of the PrintArray method declarations. For example, line 11 calls PrintArray with integerArray as its argument. At compile time, the compiler determines argument integerArray's type (i.e., Integer()), attempts to locate a method named PrintArray that specifies a single Integer() parameter (which it finds in lines 1925) and sets up a call to that method. Similarly, when the compiler encounters the PrintArray call in line 13, it determines argument doubleArray's type (i.e., Double()), then attempts to locate a method named PrintArray that specifies a single Double() parameter (which it finds in lines 2834) and sets up a call to that method. Finally, when the compiler encounters the PrintArray call in line 15, it determines argumentcharArray's type (i.e., Char()), then attempts to locate a method named PrintArray that specifies a single Char() parameter (which it finds in lines 3743) and sets up a call to that method. Study each PrintArray method. Note that the array element type (Integer, Double or Char) appears in two locations in each methodthe method header (lines 19, 28 and 37) and the For Each statement header (lines 20, 29 and 38). If we replace the element type in each method with a generic namewe chose E to represent the "element" typethen all three methods would look like the one in Fig. 25.2. It appears that if we can replace the array element type in each of the three methods with a single "generic type parameter," then we should be able to declare one PrintArray method that can display the elements of any array. The method in Fig. 25.2 will not compile because its syntax is not correctwe declare a generic PrintArray method with the proper syntax in Fig. 25.3. Figure 25.2. PrintArray method in which actual type names are replaced by convention with the generic name E (for "element"). [Note: This code will not compile.]
Figure 25.3. Printing array elements using generic method PrintArray
|