20.3 Generic Methods: Implementation and Compile-Time Translation

If the operations performed by several overloaded methods are identical for each argument type, the overloaded methods can be more 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. At compilation time, the compiler ensures the type safety of your code, preventing many runtime errors.

Figure 20.3 reimplements Fig. 20.1 using a generic printArray method (lines 22–29 of Fig. 20.3). The printArray calls in lines 14, 16 and 18 are identical to those of Fig. 20.1 (lines ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.