Part 3: Generic MethodsImplementation and
Compile-Time Translation
This is the third 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 Part 2, we presented an example using overloaded methods to motivate the need for generic methods. In this article we reimplement the overloaded methods from the example in Part 2 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.1) 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.]If the operations performed by several overloaded methods are identical for each argument type, the overloaded methods can be more compactly and conveniently coded using a generic method. You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately.
Figure 18.3 reimplements the application of Fig. 18.1 using a generic printArray method (lines 7–14). Note that the printArray method calls in lines 24, 26 and 28 are identical to those of Fig. 18.1 (lines 44, 46 and 48) and that the outputs of the two applications are identical. This dramatically demonstrates the expressive power of generics.
1 // Fig. 18.3: GenericMethodTest.java 2 // Using generic methods to print array of different types. 3 4 public class GenericMethodTest 5 {
|
Other Tutorials in This Series
Part 1: Introduction to Java Generics
Part 2: Motivation for Generic Methods in Java

