"

Introduction

Generic programming refers to writing code that will work for many types of data. It takes the idea of abstraction and applies it to algorithms. You’ve already seen an example of a generic datatype, Java’s ArrayList. The objects created when you create ArrayLists of Double, String, Color, or any other type would be almost identical, except for the substitution of one type name for another. Thus, the data type can be abstracted away. It seems silly to write essentially the same code over and over. Java’s approach to this problem is parameterized types, which is what ArrayLists use. Since it is parameterized, there are types such as ArrayList<String> to represent dynamic arrays of String, ArrayList<Color> for dynamic arrays of colors, and more generally ArrayList<T> for any object type T. ArrayList is just one class, but the source code works for many different types. This is generic programming.

The ArrayList class is just one of many standard classes that are used for generic programming in Java. We will look at some of these classes and how they are used, and we’ll see that there are also generic methods and generic interfaces. The classes and interfaces discussed in these sections are defined in the package java.util, and you will need import statements at the beginning of your programs to get access to them.

It is no easy task to design a library for generic programming. Java’s solution has many nice features but is certainly not the only possible approach. It is almost certainly not the best, and has a few features that in my opinion can only be called bizarre, but in the context of the overall design of Java, it might be close to optimal.

Learning Objectives

  • Understand Generic programming and templates
  • Understand generic methods and generic classes
  • Implement generic methods and generic classes
  • Use generic stacks and queues to solve problems

By the end of this chapter, you should be able to answer the following questions:

 

  • How do generic methods and classes take advantage of abstraction?
  • What are the strengths and weaknesses of Stacks and Queues?

License

Icon for the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

Computer Science II Copyright © by Various is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where otherwise noted.