Java Reference
In-Depth Information
20.1 Introduction
20.2 Motivation for Generic Methods
20.3 Generic Methods: Implementation
and Compile-Time Translation
20.4 Additional Compile-Time Translation
Issues: Methods That Use a Type
Parameter as the Return Type
20.5 Overloading Generic Methods
20.6 Generic Classes
20.7 Raw Types
20.8 Wildcards in Methods That Accept
Type Parameters
20.9 Wrap-Up
Summary | Self-Review Exercises | Answers to Self-Review Exercises | Exercises
20.1 Introduction
You've used existing generic methods and classes in Chapters 7 and 16. In this chapter,
you'll learn how to write your own.
It would be nice if we could write a single sort method to sort the elements in an
Integer array, a String array or an array of any type that supports ordering (i.e., its ele-
ments can be compared). It would also be nice if we could write a single Stack class that
could be used as a Stack of integers, a Stack of floating-point numbers, a Stack of String s
or a Stack of any other type. It would be even nicer if we could detect type mismatches at
compile time —known as compile-time type safety . For example, if a Stack should store
only integers, an attempt to push a String onto that Stack should issue a compilation error.
This chapter discusses generics —specifically generic methods and generic classes —which
provide the means to create the type-safe general models mentioned above.
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 overloaded methods.
3
4
public class OverloadedMethods
5
{
6
public static void main(String[] args)
7
{
8
// create arrays of Integer, Double and Character
9
Integer[] integerArray = { 1 , 2 , 3 , 4 , 5 , 6 };
10
Double[] doubleArray = { 1.1 , 2.2 , 3.3 , 4.4 , 5.5 , 6.6 , 7.7 };
11
Character[] characterArray = { 'H' , 'E' , 'L' , 'L' , 'O' };
Fig. 20.1 | Printing array elements using overloaded methods. (Part 1 of 2.)
 
 
 
Search WWH ::




Custom Search