Part 2: Motivation for Generic Methods in Java
This is the second in a series of three articles that shows how to declare and use generic methods in Java Standard Edition 5.0 (Java SE 5.0). In Part 1, we introduced the concept of generics. In this article, we present an example using overloaded methods to motivate the need for generic methods. In Part 3, we reimplement the overloaded methods from the example in this article using a single generic method. These articles are intended for students who are already familiar with Java and for Java developers.
Download the code examples for this tutorial here.
[Note: This series of three articles (Part 1, Part 2, Part 3) is an excerpt (Section 18.2) of Chapter 18, Generics, from our textbook Java How to Program, 6/e. These articles may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., JAVA HOW TO PROGRAM, ©2005, pp.870-876. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]
Overloaded methods are often used to perform similar operations on different types of data. To motivate generic methods, let’s begin with an example ( Fig. 18.1) that contains three overloaded printArray methods (lines 7–14, lines 17–24 and lines 27–34). These methods print the string representations of the elements of an Integer array, a Double array and a Character array, respectively. Note that we could have used arrays of primitive types int, double and char in this example. We chose to use arrays of type Integer, Double and Character to set up our generic method example, because only reference types can be used with generic methods and classes.
|
|
1 // Fig. 18.1: OverloadedMethods.java 2 // Using overloaded methods to print array of different types. 3 4 public class OverloadedMethods 5 { 6 // method printArray to print Integer array 7 public static void printArray( Integer[] inputArray ) 8 { 9 // display array elements 10 for ( Integer element : inputArray ) 11 System.out.printf( "%s ", element ); 12 13 System.out.println(); 14 } // end method printArray 15 16 // method printArray to print Double array 17 public static void printArray( Double[] inputArray ) 18 { 19 // display array elements 20 for ( Double element : inputArray ) 21 System.out.printf( "%s ", element ); 22 23 System.out.println(); 24 } // end method printArray 25 26 // method printArray to print Character array 27 public static void printArray( Character[] inputArray ) 28 {
|
Other Tutorials in This Series
Part 1: Introduction to Java Generics
Part 3: Generic MethodsImplementation and Compile-Time Translation

