Implementing a Generic Stack Class
Figure 20.7 declares a generic Stack
class for demonstration purposes—the java.util
package already contains a generic Stack
class. A generic class declaration looks like a nongeneric one, but the class name is followed by a type-parameter section (line 5). In this case, type parameter T
represents the element type the Stack
will manipulate. As with generic methods, the type-parameter section of a generic class can have one or more type parameters separated by commas. (You’ll create a generic class with two type parameters in Exercise 20.8.) Type parameter T
is used throughout the Stack
class declaration to represent the element type. This example implements a Stack
as an ArrayList
.
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.