Chapter 4
Generic Stacks
The previous chapter built an interface and two implementations for an integer stack. Suppose now that we need a stack to hold strings. (We are about to need one, in fact, in Section 4.4.) With copy-paste and some careful editing, we could create a StringStack interface and two corresponding string implementations. But then what if we need a stack to hold some other type? You can see the problem: continuing to write new classes and interfaces for every element type creates a lot of code that is essentially the same. What we need is a type variable, so that each time we make a new stack, we can specify the type that will be stored in it. This is known as generic programming.
4.1 Generic Types
Type Parameters
A generic ...
Get A Concise Introduction to Data Structures using Java 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.