21.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. 21.1) containing overloaded printArray
methods (lines 21–28, 31–38 and 41–48) 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 with generic methods and classes.
Get Java How to Program (early objects), 9/e 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.