O'Reilly logo

A Concise Introduction to Data Structures using Java by Mark J. Johnson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required