20.2 Motivation for Generic Methods

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. 20.1) containing overloaded printArray methods (lines 22–29, 32-39 and 42–49) that print the String representations of the elements of an Integer array, a Double array and a Character array, respectively. We could have used arrays of primitive types int, double and char. We’re using arrays of the type-wrapper classes to set up our generic method example, because only reference types can be used to specify generic types in generic methods and classes.

 1   // Fig. 20.1: OverloadedMethods.java 2   // Printing array elements using ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.